0

at the end of Doug's video on arrays he explains how variables get passed in function calls in comparison to how arrays work.

void set_array(int array[4]);
void set_int(int x);

int main (void)
{
    int a= 10;
    int b[4] = { 0, 1, 2, 3 };
    set_int(a);
    set_array(b);
    printf("%d , %d\n", a, b[0]);
}

void set_array(int array[4])
{
    array[0] = 22;
}

void set_int(int x)
{
    x = 22;
}

I think I understand the theory perfectly (huge props to Dylan's answer), but I find some difficulties in the practice; The compiler prints here 10 , 22, but why?

10 because a is the first argument of printf, defined in the first line of main. It then proceeds to print out 22 because b[0] refers to the position 0 of the array declared in the function set_array. I may have understood that 10 is because set_int(a) gets only a copy of the variable a and not the actual value. If I wanted to print 22 first, I would need to override a with the command

a = set_int(a);

Whereas 22 is because set_array(b) gets the actual value of b and therefore it is automatically overridden by the output of the function called set_array. (Otherwise it'd've printed out 0 as it's the first element of the array called b in the second line of main).

Is it correct? Can someone elaborate more and suggest other points of view for understanding better this difference?

1

For set_int() function, it's not complicated. You understand it correctly. However, things are confusing for C arrays. Actually, to me, accessing array member via bracket notation is just a syntactic sugar. Please consider the following example.

// allocate an array of integer with size of 2
int *dynmem_array = malloc(sizeof(int) * 2)

// assign values
dynmem_array[0] = 5;
*(dynmem_array + 1) = 10;

See? In this case, you can access the value either way. You can also do the same with an array on the stack memory. Therefore, by passing an array to your function, you're basically passing a pointer to the first element of your array. You don't really copy the array. That's why line array[0] = 22; replaces the original array. It jumps to that memory block then changes it.

If you can't wrap your mind around that now, it's fine. You'll learn pointers in the following weeks.

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .