c - 指向嵌套结构的指针

标签 c pointers gcc struct

这是我的代码...

#include <stdio.h>

struct one
{
    struct two
    {
            int r;
    }*b;
}*a;

void main()
{
    //struct two *new = &(*a).b;
    //new->r = 10;
    //printf("Value: %d", new->r);
    a = malloc(sizeof(struct one));
    //b = malloc(sizeof(struct two));
    (a->b)->r = 10;
    printf("Value: %d", (a->b)->r);
    return 0;

}

我在这里尝试的是,将结构定义为结构。现在这两个对象都应该是指针。我想设置r的值,然后显示它。

我唯一得到的是 Segmentation Fault 使用 gdb 我得到了关注,这似乎没有多大帮助..

(gdb) run
Starting program: /home/sujal.p/structtest/main

Program received signal SIGSEGV, Segmentation fault.
0x08048435 in main ()

我想知道如何执行提到的操作以及为什么这个东西会出现段错误。我已经尝试了一些网站上可用的可能方法,包括 Stackoverflow 的一些问题。

注释行是我未成功尝试实现目标但因相同错误而失败。

尝试下面提到的技术后进行编辑..

void main()
{
    //struct two *new = &(*a).b;
    //new->r = 10;
    //printf("Value: %d", new->r);

    //a = malloc(sizeof(struct one));
    //a my_a = malloc(sizeof*my_a);
    //my_a->b = malloc(sizeof *my_a->b);
    //my_a->b->r = 10;
    //b = malloc(sizeof(struct two));
    //(a->b)->r = 10;
    //printf("Value: %d", my_a->b->r);

    a = (one*)malloc(sizeof(struct one));
    a->b = (one::two*)malloc(sizeof(struct one::two));
    (a->b)->r = 10;
    printf("Value: %d", (a->b)->r);
    return 0;

}

我已经尝试了所有提到的技术,但它们给我错误。我得到的最后一个错误如下。

new.c: In function âmainâ:
new.c:24:7: error: âoneâ undeclared (first use in this function)
new.c:24:7: note: each undeclared identifier is reported only once for each function it     appears in
new.c:24:11: error: expected expression before â)â token
new.c:25:13: error: expected â)â before â:â token
new.c:25:20: error: expected â;â before âmallocâ
new.c:28:2: warning: âreturnâ with a value, in function returning void [enabled by default]

最佳答案

您正在取消引用未初始化的指针。

你需要先分配一个struct one的实例:

a = malloc(sizeof *a);

然后你可以初始化成员b:

a->b = malloc(sizeof *a->b);

然后你就可以访问r了:

a->b->r = 10;

Here is a working solution, by adapting your code with my answer .

关于c - 指向嵌套结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15922878/

相关文章:

c++ - std::wstring 指针赋值 C++

c++ - 在段错误之前缺少 cout

c - C 中的泛型结构

c - 使用堆栈从数组中删除最后输入的偶数

c - 如何在 GLSL 中使用指针

c - 我如何获得有关 malloc() 行为的信息?

c - 将数组分配给C中的结构成员

c - C 中的胖指针

c - Glibc 和 uClibc 并排在一个系统上

c - 'asm' 、 '__asm' 和 '__asm__' 之间有什么区别?