对结构在内存中的位置感到困惑

Confused about a struct's location in memory

我正在探索指针,目前正在搞乱结构指针。目前,我有这个代码:

#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 个输出,使用 charint 指针算法,但是我很困惑为什么它 returns 0x0 对于 struct 指针的内存地址?另外,如果我想要内存中的 double y 的地址,我将如何打印它?

你的代码调用了未定义的行为,因为你所有的指针都被使用未初始化

在启用警告的情况下编译(例如 -Wall 用于 GCC)并将得到:

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

当您声明一个指针时,您必须为其分配内存,或者如果您不使用它,则将其设置为 null。

pc = malloc(sizeof(*pc));
pi = malloc(sizeof(*pi));
pp = malloc(sizeof(*pp));

不要忘记验证 malloc 的 return 值!!!! (不是故意的)

您应该使用 -W -Wall -Wextra -g 编译,然后 运行 使用 valgrind 编译二进制文件。

此外,您不需要强制转换为 void *,因为它已经是一个指针

这是结果:

0xf88010

0xf88011

0xf88030

0xf88038

0xf88050

0xf88020