任何人请详细说明这里发生了什么?
int main()
{
int **p = 0;
//p=? and why| *p=? and why|**p=? and why
++p;
//p=? and why| *p=? and why|**p=? and why
printf("%d\n", p);
return 1;
}
输出:-
- 4(为什么?)
任何人请详细说明这里发生了什么?
int main()
{
int **p = 0;
//p=? and why| *p=? and why|**p=? and why
++p;
//p=? and why| *p=? and why|**p=? and why
printf("%d\n", p);
return 1;
}
输出:-
首先,p是一个指向整数的指针。
int **p = 0;
p= 0,*p= 没有,**p= 少于没有。
++p;
与 p = p + 1 相同。表示一个指向指向 int 的指针的指针的大小。至少在您的操作系统上,指针基本上是 32 位长度(4 字节)。p现在在 0 之后指向 4 个字节。 的p值为4。
p is a pointer to a pointer-to-int. It's being initialised to 0, i.e. it's a null pointer.
It's then being incremented to point at the next consecutive pointer-to-int in memory.* The next pointer will be at address 4, because on your platform the size of a pointer is 4 bytes.
Then printf interprets the pointer value as an integer, and so displays "4".
* Note, however, that this is now undefined behaviour.
It is clear. You have a pointer to a pointer to int (int **p means a pointer to a pointer to int), that actually holds the address 0). A pointer in itself, in your architecture, is 32 bits (4 bytes) long, so incrementing p gives you p+4, that is, 0+4 = 4.
Go get a nice C book and learn about pointer arithmetic. You'll be glad the rest of your life! :)
++p实际上是未定义的行为,但是在您的实现中似乎发生的sizeof(int*)是 4,并且空指针是地址 0。回想一下,当它不是 UB 时,指针增量会向地址添加等于大小的字节数引用类型。因此,当您获取一个类型为空的指针int**(因此引用类型为int*)并递增它时,您最终会到达 address ,这并不奇怪4。只是不能保证。
%d当格式期望 an时传递指针int也是未定义的行为,但似乎intand的表示int**足够兼容,并且实现上的可变参数调用约定对它们的处理方式非常相似,它已成功打印4。sizeof(int) == sizeof(int**)对于, 但也不能保证的实现,这也不足为奇。
当然,由于它是未定义的行为,因此您所看到的还有其他可能的解释。
p 是指向 int 的指针。并且它被初始化为0,即NULL。
当你递增它时,它现在指向指向 int 的下一个指针,在 32 位系统上,它恰好是 4。