Search code examples
cmemoryvariable-assignmentassignment-operator

Multiple one line assignments with malloc in c


Suppose the below statement:

int *numbers, *inverse;
numbers = inverse = (int *)malloc(n * sizeof(int));

I am curious to know what is going on here - I know it is right to left, so first the memory for inverse is being allocated. Then I set numbers equal to inverse, will that mean that the memory location of numbers will be the same as inverse? Or does it allocate the same amount of memory at locations &numbers and &inverse?

For example, if I do something like inverse[i] = 5 will that mean that numbers[i] == 5?


Solution

  • You have:

    int *numbers, *inverse;
    numbers = inverse = (int *)malloc(n * sizeof(int));
    

    That's the same as writing:

    int *inverse = (int *)malloc(n * sizeof(int));
    int *numbers = inverse;
    

    The variable numbers simply has a copy of the pointer that is in inverse — it points to the same place. However, you might be about to iterate through the array with one pointer while returning the other from the function, which could be a good reason for having the two copies.

    There's a single memory allocation; there will need to be a single call to free() to release the allocated memory. The value passed to free() will be the same as the original value assigned to either inverse or numbers.

    You also ask:

    If I do something like inverse[i] = 5 will that mean that numbers[i] == 5?

    If you've not changed the value stored in either inverse or numbers, and if i is in the range 0 .. (n-1), then after the assignment, the equality will hold. The pointers are the same (same type, same value), so indexing them produces the same result. It also means inverse[i] == numbers[i] of course.