开发者

C Array Question

When a simple variable name is used as an argument passed to a function, the function takes the value corresponding to this variable name and installs it as a new variable in a new memory location created by the function for that purpose. But what happens when the address of an array is passed to a function as an argument? Does the function create another array and move the values into it from the array in the calling开发者_如何学Go program?


No, if you pass the address of something to a function, the function gets the address. Technically, it gets a copy of the address (it's all pass-by-value, we just use pointers to simulate pass-by-reference) so that, if you change that address within the function, that has no effect on return.

By dereferencing the address, you can change the thing it points to. For example:

void changeValA (int x) {
    x = 42;                  // x is 42 but a is unchanged.
}
void changeValB (int *x) {
    *x = 42;                 // *x (hence a) is now 42
}
:
int a = 31415;               // a is 31415
changeValA (a);              // a is still 31415
changeValB (&a);             // a is now 42

Passing the address of an array is pretty much the same as passing the array itself. Under those circumstances, the array decays to the address of its first element.


No.

When an array is passed to a function, it decays to a pointer to the first element of the array. This allows the function to access the array elements exactly like the original code, including the ability to modify the elements that comes with passing a pointer to a function, but loses the ability to know the compile-time size of the array with sizeof.

Basically, this:

void func(int a[]);

// ...

int i[] = { 0, 1, 2, 3, 4 };
func(i);

Is effectively doing this:

void func(int *a);

// ...

int i[] = { 0, 1, 2, 3, 4 };
func( & (i[0]) );

Note that the function receiving the array has no way of knowing how long it is because of this. That's why almost all functions that take arrays (or pointers) also take a size parameter.


The numeric value of the address will be copied to the stack, not the memory space that the address points to!


The name of an array can be treated as a pointer to its start. So when you pass the array to a function, it's as if you were passing a pointer. No new array is created.


No. Only the reference/address of the array will go. So any update within the function on the array will affect the passed array.


In C, an array is always passed by reference (i.e. only the pointer to its beginning is passed).

If you really want to pass an array by value, you can wrap it in a struct, and pass the struct. There is no other way to pass an array by value.


No when you pass an address of an array (I believe you are talking about pointers) the copy of the pointer is passed to the function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜