0

如何在C中将数组作为参数传递?

int a,b,c[10];
void Name1(int x, int y, int *z)
{
    a = x;
    b = y;
    c = z;
}

我尝试将它作为参数传递,但它没有构建,如何修复它?

的声明void Name1(int x, int y, int *z);是否与 相同void Name1(int x, int y, int z[])?将被编译器void Name1(int x, int y, int z[])视为?void Name1(int x, int y, int *z);

4

4 回答 4

1

当您将数组作为参数传递给函数时,它会衰减为指向其第一个元素的指针。

所以,

void Name1(int x, int y, int *z)

将工作。
但是数组是不可分配的,所以:

c = z;

不起作用,您需要将每个数组元素从源显式复制到目标。

于 2013-06-02T17:49:44.597 回答
0

There are a couple of answers here, but I don't think any of them are completely sufficient, so...

basically you can either copy the array or use the pointer, but either way you will need to keep track of the length.

int a,b, *c, len;

void Name1(int x, int y, int *z, int z_len)
{
    a = x;
    b = y;
    c = z;
    len = z_len;
}

//usage: 
int arr[5];

Name1(1,2,arr /* or &arr[0] ,*/, sizeof(arr )/ sizeof (int));

if you never need to add items this will be sufficient... If you do it gets more complicated...

it is important to keep the length around so that you know how many elements you have, even if you are going to copy them.

于 2013-06-02T19:08:46.827 回答
0
c=z; is invalid

c 指针没有内存来保存 z 地址。

你可以说:

int a,b,*c;    
c=(int *)calloc(10,sizeof(int) );
void Name1(int x, int y, int *z)
{
  a = x;
  b = y;
  c = z;
}
于 2013-06-02T20:37:41.477 回答
0

这样做c = z;,您正在分配一个非左值,这是不允许的。这就像在做&c[0] = &z[0];

于 2013-06-02T18:27:29.203 回答