I am learning C in linux and using GCC compiler. I have a following piece of code to understand the pointers in C.
我在linux中学习C并使用GCC编译器。我有一段代码来理解C中的指针。
int main(void)
{
int n;
/*long int z;*/
int a=1025;
int* p;
//int* ptr=&n;
p=&a;
n=sizeof(double);
//printf("\nAddress of n is =%p",&n);
printf("\nsize of integer is %d",n);
printf("\nAddress of a is =%p, value of a is= %d",&a,*p);
printf("\nAddress of a is =%p, value of a is= %d",p,*p);
printf("\nAddress of this location is is =%p, value at this location is= %d",(p+1),*(p+1));
}
OUTPUT
size of integer is 8
Address of a is =0x7ffd56375f90, value of a is= 1025
Address of a is =0x7ffd56375f90, value of a is= 1025
Address of this location is is =0x7ffd56375f94, value at this location is= 8
for the last printf statement why the value comes as 8. shouldnt it be a garbage value?
对于最后一个printf语句,为什么值为8.它不应该是垃圾值吗?
1 个解决方案
#1
0
my compiler is giving this one for last printf
我的编译器为最后一个printf提供了这个
Address of this location is is =0xbfc283b8, value at this location is= -1077771340
it's garbage. you are trying to access data from p+1 location, we don't know what is there at p+1, if that memory is reserved for someone else you may get segmentation fault also. So I think it's undefined behaviour if you de-reference unreserved memory.
这是垃圾。你试图从p + 1位置访问数据,我们不知道p + 1有什么,如果那个内存是为别人保留的,你也可能会得到分段错误。因此,如果您取消引用未预留的内存,我认为这是未定义的行为。
#1
0
my compiler is giving this one for last printf
我的编译器为最后一个printf提供了这个
Address of this location is is =0xbfc283b8, value at this location is= -1077771340
it's garbage. you are trying to access data from p+1 location, we don't know what is there at p+1, if that memory is reserved for someone else you may get segmentation fault also. So I think it's undefined behaviour if you de-reference unreserved memory.
这是垃圾。你试图从p + 1位置访问数据,我们不知道p + 1有什么,如果那个内存是为别人保留的,你也可能会得到分段错误。因此,如果您取消引用未预留的内存,我认为这是未定义的行为。