我创建了指向指针和int数组的指针,但是当我试图通过指针访问数组时,它跳过一些元素并一次由两个元素移动(例如:从1到3)。这是我的代码:
int main(void) {
int c=10;
int p[5]={2,3,5,6,8};
int *x;
int **y;
x=p;
y=&p;
printf("p value is %d and p points to %d",p,&p);
printf("\n x is %d \n",x[1]);
printf("\n y is %d \n",y[0]);
return 0;
}当我打印y[1]时,它会打印5而不是3,y[2]被打印为8,我想不出原因。有人能帮我吗?指针x运行良好,并沿着x[0]=2、x[1]=3、x[5]=5等正确的元素移动。还有谁能解释一下为什么p和p的值相同?
发布于 2013-08-25 07:07:28
这至少提供了一个清晰的编译,并使用%p打印指针:
#include <stdio.h>
int main(void)
{
int p[5]={2,3,5,6,8};
int *x = p;
int **y = &x;
printf("p value is %p and the address of p is %p and p points to %d\n", (void *)p, (void *)&p, *p);
printf("x[1] is %d\n", x[1]);
printf("y[0] is the address %p\n", (void *)y[0]);
printf("y[0][0] is %d\n", y[0][0]);
return 0;
}示例输出(Mac 10.8.4,GCC 4.8.1,64位编译):
p value is 0x7fff5a1a54d0 and the address of p is 0x7fff5a1a54d0 and p points to 2
x[1] is 3
y[0] is the address 0x7fff5a1a54d0
y[0][0] is 2https://stackoverflow.com/questions/18426474
复制相似问题