[英]I don't understand C pointers
I don't really understand the reason why I obtain a different address from what I'm expecting.我真的不明白为什么我获得的地址与我期望的不同。
I've tried to build this small C code with -m32
flag option.我尝试使用
-m32
标志选项构建这个小 C 代码。
#include <stdio.h>
#include <stdlib.h>
char *Buffer[10];
int main (void){
printf("%p\n", Buffer);
char *Buffer2 = Buffer + 6;
printf("%p\n", Buffer2);
}
Expected output:预期输出:
Buffer = 0x56559040
Buffer2 = 0x56559046
Obtained output:获得的输出:
Buffer = 0x56559040
Buffer2 = 0x56559058
Why the obtained output is different from the expected one (0x56559040 + 6 = 0x56559046)?为什么获得的输出与预期的不同(0x56559040 + 6 = 0x56559046)?
The difference between these two values这两个值的区别
Buffer = 0x56559040
Buffer2 = 0x56559058
is 0x18
or in decimal 24
.是
0x18
或十进制24
。
In this declaration在本声明中
char *Buffer2 = Buffer + 6;
the array designator Buffer
is converted to pointer to its first element.数组指示符
Buffer
被转换为指向其第一个元素的指针。 As the element type of the array Buffer
is char *
then the expression has the type char **
.由于数组
Buffer
的元素类型是char *
因此表达式的类型为char **
。
There is no implicit conversion between types char *
(the type of the variable Buffer2
) and char **
(the type of the initializer)类型
char *
(变量Buffer2
的类型)和char **
(初始化器的类型)之间没有隐式转换
So the compiler should issue at least a warning.所以编译器至少应该发出警告。
Nevertheless using the pointer arithmetic this expression然而使用指针算术这个表达式
Buffer + 6
is evaluated like被评估为
the value of the address pointed to by Buffer + 6 * sizeof( char * )
as the size of a pointer of the type char *
(the size of element of the array) in your system is equal to 4
then you get the value 0x56559058 that is由于系统中
char *
类型的指针(数组元素的大小)的大小等于4
那么您将得到值 0x56559058,即
0x56559040 + 6 * sizeof( char * )
^^^^^^^^^^^^^^^^
4
That is the expression这就是表达
Buffer + 6
points to the sixth element of the array Buffer.指向数组 Buffer 的第六个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.