【发布时间】:2013-04-10 10:07:55
【问题描述】:
这是我的代码...
#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]
【问题讨论】: