【问题标题】:Accessing a member in a struct?访问结构中的成员?
【发布时间】:2014-11-30 03:20:34
【问题描述】:

如果我有以下结构:

struct myStruct {
    int value;
    struct myStruct *next;
};

并且有一个实例被定义为

struct myStruct *the_struct = (void *) malloc(sizeof(struct myStruct))

如何访问 *next 的“值”?


我试过做

the_struct->next.value

*(the_struct->next)->value

但我收到错误“取消引用指向不完整类型的指针”。

【问题讨论】:

标签: c pointers struct


【解决方案1】:

你应该使用

 the_struct->next->value

但在此之前,您应该确保the_struct->next 有效。

顺便说一句,malloc(3) 确实失败了,它会在成功时提供一个 未初始化 内存区域。所以还要阅读perror(3)exit(3),然后代码:

struct myStruct *the_struct = malloc(sizeof(struct myStruct));
if (!the_struct) 
  { perror("malloc myStruct"); exit(EXIT_FAILURE); };
the_struct->value = -1;
the_struct->next = NULL;

(或者,使用memset(3)malloc成功 结果的每个字节都归零,或者使用calloc 而不是malloc)。

稍后,您还可以获取并初始化 struct myStruct* next_struct,最后分配 the_struct->next = next_struct;,然后您可以例如分配the_struct->next->value = 32;(或者,在这种特殊情况下,等效的next_struct->value = 32;

请编译所有警告和调试信息 (gcc -Wall -g) 并了解如何使用调试器 (gdb)。在 Linux 上,也可以使用 valgrind

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 2023-03-22
    • 2017-06-11
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多