我有一个指向数组的指针,无法访问数组的成员。要使其更精确,请参阅下面的代码:
int struc[2] = {6,7};
int (*Myval)[2];
Myval =&struc;
Now the Myval is pointing to the start of the array and upon dereferencing the pointer we would get the 1st element of the array i.e
printf("The content of the 1st element is %d\n",(*Myval[0]));
gives me the first elemnt which is 6.
How would i access the 2nd elemnt of the array using the same pointer.
如果我做Myval++,它将增加8,因为数组的大小是8。
有什么建议或想法吗??
谢谢和问候
马迪
最佳答案
我认为,虽然int (*)[2]
是指向两个int
s的数组的有效类型,但对于您所需要的内容来说,这可能是过分的,即访问数组成员的指针类型。在这种情况下,只需要一个指向数组中整数的简单int *
。
int *p = struc; // array decays to pointer to first element in assignment
p[0]; // accesses first member of the array
p[1]; // accesses second member of the array
正如其他人所指出的,如果确实使用指向数组的指针,则在对结果数组使用下标操作之前,必须取消对指针的引用。
int (*Myval)[2] = &struc;
(*Myval)[0]; // accesses first member of the array
(*Myval)[1]; // accesses second member of the array
“declaration mirrors use”的C声明语法在这里有帮助。
关于c - 指向数组的指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1147477/