嵌套结构的指针

时间:2013-04-10 10:07:55

标签: 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 ()

我想知道如何执行上述操作以及为什么这个东西会出现Segmentation故障。我已尝试过在某些网站上提供的可能方法,包括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]

4 个答案:

答案 0 :(得分:9)

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

您需要先分配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

答案 1 :(得分:0)

你得到一个SIGSEGV因为第二个解除引用的指针

(a->b)->r

未初始化/定义

解决您需要执行的问题

struct two
{
        int r;
}

struct one
{
 two *b;
};

one *a;

...

a = malloc(sizeof(struct one));
a->b = malloc(sizeof(struct two));

a->b->r = 10;
printf("Value: %d", a->b->r);
return 0;

答案 2 :(得分:0)

添加@Quonux答案,我还要定义类型:

typedef struct
{
    int r;
} t_two;

typedef struct
{
    t_two *p_b;
} t_one;

void main()
{
    t_one *p_a;

    p_a = malloc(sizeof(t_one);
    p_a->p_b = malloc(sizeof(t_two));

    p-a->p_b->r = 10;

    printf("Value: %d", p_a->p_b->r);
    return 0;

}

答案 3 :(得分:-1)

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