在我下面的代码中,为什么 ptr[0]
的值和地址是相同的。 ptr[1]
和 ptr[2]
的行为相同。
#include<stdio.h>
int main()
{
int var=100;
int(*ptr)[5];//array of pointer.
ptr=&var;
printf("Value of var is : %d\n",var);
printf("Address of var : %u\n",&var);
printf("Value inside ptr after ptr=&var : %u\n",ptr[0]);
printf("Value of ptr[0] is : %d\n", ptr[0]);
printf("Adress of ptr[0] is : %u\n",&ptr[0]);
printf("Value of ptr[1] is : %d\n",ptr[1]);
printf("Adress of ptr[1] is : %u\n",&ptr[1]);
printf("Value of ptr[2] is : %d\n",ptr[2]);
printf("Adress of ptr[2] is : %u\n",&ptr[2]);
return 0;
}
最佳答案
在你的情况下
int(*ptr)[5];//array of pointer.
不完全是“指针数组”。。相反,它是一个指向 5 个 int
数组的指针。
所以,
ptr=&var;
是错误的,因为 &var
不是指向数组的指针。
然后,由于越界访问,访问ptr[1]
是绝对错误的。 ptr
本身并不是一个数组。
你可能想重写
int(*ptr)[5];
作为
int *ptr[5];
也就是说,
int main()
应该是int main(void)
,按照标准。- 始终使用
%p
打印地址。此外,在作为参数传递之前,将指针转换为(void *)
,因为%p
需要一个void *
。
关于c - 在我下面的代码中,为什么 ptr[0] 的值和地址相同。 ptr[1] 和 ptr[2] 的行为相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31333702/