简体   繁体   English

将指针作为数组传递给C中的函数?

[英]Pass a pointer as array in function in C?

void f(int *a, int n)
{
     int i;
     for (i = 0; i < n; i++)
     {
         printf("%d\n", *(a+i));
     }
 }

The above code worked ok if in main() I called: 如果在main()我调用了上面的代码就可以了:

int a[] = {1,2,3};
int *p = a;

f(a, 3);

But if in main() , I did: 但如果在main() ,我做了:

int *a =(int*) {1,2,3};

f(a, 3);

Then, the program will crash. 然后,程序将崩溃。 I know this might look weird but I am studying and want to know the differences. 我知道这可能看起来很奇怪,但我正在研究并希望了解其中的差异。

It's because of the cast. 这是因为演员。 This line says: 这条线说:

int *a =(int*) {1,2,3};

Treat the array {1,2,3} as a pointer to an int. 将数组{1,2,3}视为指向int的指针。 On a 32 bit machine, the value of the pointer is now 1 , which is not what you want. 在32位机器上,指针的值现在为1 ,这不是您想要的。

However, when you do: 但是,当你这样做时:

int *p = a;

The compiler knows that it can decay the array name to a pointer to it's first element. 编译器知道它可以将数组名称衰减为指向它的第一个元素的指针。 It's like you'd actually written: 这就像你实际上写的:

int *p = &(a[0]);

Similarly, you can just pass a straight in to the function, as the compiler will also decay the array name to a pointer when used as a function argument: 同样,你可以通过a直的功能,作为函数参数一起使用时,编译器也将衰减数组名的指针:

int a[] = {1,2,3};
int *p = &(a[0]);

f(p, 3) 
f(a, 3); // these two are equivalent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM