我正在探索指针,目前正在搞乱结构指针。目前,我有这段代码:
#include <stdlib.h>
#include <stdio.h>
struct point{
double x;
double y;
};
int main(){
char *pc;
int *pi;
struct point *pp;
//char pointer
printf("%p\n\n", (void*)pc);
pc++;
printf("%p\n\n", (void*)pc);
//int pointer
printf("%p\n\n", (void*)pi);
pi += 2;
printf("%p\n\n", (void*)pi);
//struct pointer
printf("%p\n\n", (void*)pp);
pp -= 3;
printf("%p\n\n", (void*)pp);
}
这段代码的输出是这样的:
0x104978036
0x104978037
0x7fff5ec4bbc8
0x7fff5ec4bbd0
0x0
0xffffffffffffffd0
我理解前 4 个输出,使用 char
和 int
指针算法,但是我很困惑为什么它返回 0x0
struct
指针的内存地址?另外,如果我想要内存中的地址,double y
,我将如何打印它?
最佳答案
您的代码调用了未定义的行为,因为您使用的所有指针都未初始化!
在启用警告的情况下编译(例如 GCC 的 -Wall
),将得到:
prog.c: In function 'main':
prog.c:15:5: warning: 'pc' is used uninitialized in this function [-Wuninitialized]
printf("%p\n\n", (void*)pc);
^~~~~~~~~~~~~~~~~~~~~~~~~~~
prog.c:20:5: warning: 'pi' is used uninitialized in this function [-Wuninitialized]
printf("%p\n\n", (void*)pi);
^~~~~~~~~~~~~~~~~~~~~~~~~~~
prog.c:25:5: warning: 'pp' is used uninitialized in this function [-Wuninitialized]
printf("%p\n\n", (void*)pp);
^~~~~~~~~~~~~~~~~~~~~~~~~~~
像这样初始化你的指针,例如:
char c = 'a';
char *pc = &c;
int i = 5;
int *pi = &i;
struct point p;
struct point *pp = &p;
并且可以获得:
0x7ffe629c90d7 // address of the charatcer
0x7ffe629c90d8 // sizeof(char) is 1
0x7ffe629c90d0 // address of the integer
0x7ffe629c90d8 // sizeof(int) is 8 in this system
0x7ffe629c90c0 // address of the struct
0x7ffe629c9090 // sizeof(struct point) is 16 in this system
// 0x7ffe629c90c0 - 0x7ffe629c9090 = 0x30 -> Decimal: 48 = 3 * 16
关于对结构在内存中的位置感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46292256/