I thought arrays would be call by reference. So the allocation should have an effect outside of the method.
C doesn't have call-by-reference like C++ does. The best C can do is to simulate it using pointers; which is the reason why arrays may appear to behave this way. What they're pointing to, the actual array contents, is (effectively, if not technically) being passed by reference. But the array pointer itself is *not*---the pointer is being copied by value.
In order to make a method as you are attempting, you either need to make the parameter an int**, or you need to make the return value of the function be the new pointer. The second is the approach taken by the realloc() method, incidentally.
int main(int argc, char ** argv)
{
int test[3] = {0,0,0};
printf("%d,%d,%d \n",test[0],test[1],test[2]);
arrayTest(test,3);
printf("%d,%d,%d \n",test[0],test[1],test[2]);
}
It looks like the array is passed by reference?
My question qas probably not well explained: This code produces
0 0 0
1 1 1
as output. So it seems that the array is passed as reference (effectively not technically as I understand)?
But you said that arrays are passed as value. This is why I am confused...
You shouldn't talk about an array being passed to the function. The array is *not* what's being passed. Instead, your are passing a pointer to the array.
The pointer itself is passed by value, so modifications to the pointer inside the function are not reflected afterwords. But the address held by the pointer is the same whether you're working from a copy of the pointer or not; so you're free to modify that memory at will, and it will be reflected outside the function.
Think of it like a dog on a leash. You can put as many leashes as you like on the same dog, and changes made to one leash won't affect any of the others. But they're all attached to the same dog. If you attach one of the leashes to a second dog, that doesn't affect anything relating to any of the leashes attached to the first. In this analogy, leashes are pointers and dogs are the arrays they're directed at.
Last edited by Lindley; November 8th, 2009 at 11:57 AM.
Bookmarks