pointer to an array in c
The below program gives me an error in the intialisation (*a)[5]=((*)[])&v;.
When I don't type at that line then I'm still getting the error.
int main()
{
int v[10];
int **p;
int (*a)[5];
(*a)[5]=((*)[])&v;
printf("%d\n",*a);
printf("%d\n",sizeof(v开发者_JS百科));
return 0;
}
&v is a reference to the int array v, so it is of type int ** (essentially). int (*a)[5] means you're declaring a pointer to an array of 5 ints. BUT, in the next line, when you write, (*a)[5], it means you are dereferencing a to get an int pointer, and then dereferncing again to access the element stored at [5]. but arrays in C are zero indexed, so you can only access [0] to [4], and [5] is not allocated.
You want a = &v. This will make a a pointer to the int pointer v. There are other issues like *a is an int pointer so "%d" won't fly, you haven't given any values to a or v, ((*)[]) is just unnecessary, etc.
When you mean error, you probably refer to run-time error. int (*a)[5] is a pointer to an array of 5 ints, which is never initialized. However on the next line you try to dereference it. You should initialize 'a' before using it, you may be trying to initialize it with v but that's not an array of 5 ints. If you were to redeclare v as int v[5] then a = &v should work.
Assignment to variable a should only have a on the LHS.
I think it is simpler than you are expecting
#include <stdio.h>
int main()
{
int v[10];
int **p;
int *a[5];
v[0] = 1234;
a[0] = v;
printf("%d\n", *a[0]);
printf("%d\n", sizeof(v));
return 0;
}
*a[5] is an array of int * pointers. v[10] is effectively also a pointer to an int.
So *a and a[0] are effectively the same thing.
ETA: Perhaps printf("%d\n", a[0][0]); is better
加载中,请稍侯......
精彩评论