tags:

views:

91

answers:

4

The following code is trying to make a point (probably the difference between arrays and local variables) I only have a vague idea on the code. Would someone please elaborate? Thanks

void doit(int x[10], int y) {
    y = 30;
    x[0] = 50;
}

void main(void) {
    int x[10];
    int y = 3;
    x[0] = 5;
    printf("x[0] is %d and y is %d\n", x[0], y);
    doit(x, y);
    printf("x[0] is %d and y is %d\n", x[0], y);

}
+4  A: 

It is showing that arrays are not really passed directly to functions - instead, the address of the first member of the array is passed.

That means that if the called function modifies the array that was "passed", it is modifying the original array in the caller.

On the other hand, when the called function modifies the plain int parameter y, it is modifying a local copy of the variable, and the change is not reflected in the caller.

caf
A: 

Local variables are passed as value where as in arrays the reference is passed not the actual values. so when you change the value in child array the parent array will get changed. Arrays are same as pointers in using the reference

Sri Kumar
Not quite. All non-array expressions are passed by value, and array expressions are passed by address. In other words, any expression having an array type gets converted into a pointer automatically.
Loadmaster
+1  A: 

y is passed by value meaning that a temporary copy is created, you have to pass it as a pointer to modify it:

void doit(int x[10], int* y) {
    *y = 30;
    x[0] = 50;
}

Declaring an array is also not really needed. The compiler anyway understands only that it is a pointer and does (usually) not check the boundaries.

void doit(int* x, int* y) {
    *y = 30;
    x[0] = 50;
}
jdehaan
+3  A: 

In C, all arguments are passed by value. However, arrays decay into a pointer to the first element to the array when they get passed; the result is effectively as if the array was passed by reference.

In your code, the doit() function can mutate the array pointed to by x, but it cannot mutate the simple int value in y.

Daniel Pryden