在下面的代码中,为什么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 : %dn",var);
printf("Address of var : %un",&var);
printf("Value inside ptr after ptr=&var : %un",ptr[0]);
printf("Value of ptr[0] is : %dn", ptr[0]);
printf("Adress of ptr[0] is : %un",&ptr[0]);
printf("Value of ptr[1] is : %dn",ptr[1]);
printf("Adress of ptr[1] is : %un",&ptr[1]);
printf("Value of ptr[2] is : %dn",ptr[2]);
printf("Adress of ptr[2] is : %un",&ptr[2]);
return 0;
}
在您的案例中,
int(*ptr)[5];//array of pointer.
不完全是"指针数组">。相反,它是指向5个int
s数组的指针。
所以,
ptr=&var;
是错误的,因为&var
不是指向数组的指针。
那么,由于越界访问,访问ptr[1]
是绝对错误的。这里的ptr
本身并不是一个数组。
您可能需要重写
int(*ptr)[5];
作为
int *ptr[5];
也就是说,
- 根据标准,
int main()
应为int main(void)
- 始终使用
%p
打印地址。此外,在作为参数传递之前,将指针强制转换为(void *)
,因为%p
需要void *
int(*ptr)[5];//array of pointer.
ptr=&var;
无法编译错误:从不兼容的类型"int*"分配给"int(*([5]">。ptr
不是int
指针,而是指向5个整数数组的指针,因此它们不适合赋值。
即使你用显式强制转换编译器,这个
printf("Value inside ptr after ptr=&var : %un",ptr[1]);
显然是未定义的行为,因为您的访问权限超出了允许的范围。
为什么ptr[0]的值和地址是相同的
一旦你有了不明确的行为,所有的赌注都会落空!请阅读有关未定义行为的内容。
指针的值可以通过打印来确定。
*ptr[0]
因为这是正确的语法。此外,如果您使用打印prt[0]的地址
&ptr[0]
它将给出与var变量相同的地址,因为它将自动为变量赋值整数数组中的第0个索引。要检查结果,您可以使用下面修改后的代码。
#include <stdio.h>
int main()
{
int var=100;
int(*ptr)[5];
ptr=&var;
printf("Value of var is : %dn",var); // it will print 100.
printf("Address of var : %un",&var); // it will print an address.
printf("Value inside ptr after ptr=&var : %un",*ptr[0]); // it will print 100.
printf("Value of ptr[0] is : %dn", *ptr[0]); // it will print 100.
printf("Address of ptr[0] is : %un",&ptr[0]); // it will print the address same as var.
printf("Value of ptr[1] is : %dn",*ptr[1]); // it will print garbage value.
printf("Address of ptr[1] is : %un",&ptr[1]); // Address.
printf("Value of ptr[2] is : %dn",*ptr[2]); // garbage value
printf("Address of ptr[2] is : %un",&ptr[2]); // Address.
return 0;
}
这是我的输出。
Value of var is : 100
Address of var : 1386442756
Value inside ptr after ptr=&var : 100
Value of ptr[0] is : 100
Address of ptr[0] is : 1386442756
Value of ptr[1] is : -87802171
Address of ptr[1] is : 1386442776
Value of ptr[2] is : 32767
Address of ptr[2] is : 1386442796