Search code examples
cpointersmallocstorage-duration

Stack VS Heap, what goes where here?


So I started playing around with C and having a lot of fun thus far.

There are however a couple of things I can not wrap my head around.

I know that this will end up on the stack

int i = 0;

I know this will reserve space for an integer on the heap and return the adress

int *i = malloc(sizeof(int));

However. If i do this

int i_one = 1, i_two = 2;
int *arr = calloc(2, sizeof(int));
arr[0] = i_one;
arr[1] = i_two;

i_one and two are stack allocated while arr is on the heap. Does this mean that arr will copy the values of i_one and two on to the heap or will it simply hold 2 references to variables on the stack. Im assuming its a variant of alt one considering (if I'm not misstaken) my stack allocated ints will be freed as soon as I exit this function.

So to summarize, when creating a dynamically allocated array using calloc. Do the entries in the array need to be pointers / heap allocated as well? In my head that would not make sense because then wouldnt i create an array of int pointers instead? And yes I know the size of a pointer is the same as an int so the example is a bit stupid but you get the point.

Thank you


Solution

  • The assignment operator is designed to assign a value stored in one object to another object.

    So in these assignment statements

    arr[0] = i_one;
    arr[1] = i_two;
    

    values stored in the variables i_one and i_two are copied into the memory occupied by the array elements arr[0] and arr[1]. Now if you will change for example the value stored in the variable i_one then the value stored in arr[0] will not be changed.

    If you want to store references to objects i_one and i_two in the heap then you should write

    int **arr = calloc(2, sizeof(int *));
    arr[0] = &i_one;
    arr[1] = &i_two;
    

    Now you can change for example the value stored in i_one by means of the array element arr[0] the following way

    *arr[0] = 10;