指向数组的指针

时间:2009-07-18 12:51:25

标签: c pointers

我有一个指向数组的指针,我无法访问数组的成员。要使其更精确,请参阅下面的代码:

       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。 任何建议或想法??

谢谢和问候 麦迪

3 个答案:

答案 0 :(得分:4)

我认为虽然int (*)[2]是一个指向两个int数组的有效类型,但它可能对你所需要的东西有些过分,这是一种用于访问成员的指针类型。阵列。在这种情况下,只需要指向数组中整数的简单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

'声明镜像使用'的C声明语法在这里有帮助。

答案 1 :(得分:2)

你不会取消引用,而是下标,就像其他指针一样

Myval[0][1] // accesses second element

第一个[0]可能有点令人困惑,因为它表明你正在处理一个数组。为了明确你正在使用指针,我会使用解除引用

(*Myval)[1] // accesses second element

(*Myval)取消引用数组指针并生成数组,以下的下标操作可以解析和解引用您想要的项目。

答案 2 :(得分:0)

这也应该有效:

*( Myval[0] + 1 )