这里是我的代码...指针嵌套结构
#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
的值然后显示它。
的唯一的事情我使用gdb
我得到了下面的,这似乎没有多大帮助得到它Segmentation Fault
..
(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]
这是我得到的一个错误.. 。new.c:在函数中“mainâ: new.c:17:4:错误:预期““my_aâ new.c:18:2:错误:âmy_aâ未声明(首次在此函数中使用) 新。 c:18:2:注意:每个未声明的身份每个功能只会报告一次,它会在 新出现。c:18:12:警告:内置函数的不兼容隐式声明:默认情况下启用 new.c:22:2:错误:预计在之前打印出来 new.c:23:2警告: âreturnâ有一个值,在函数返回void [默认情况下启用]' – 2013-04-10 10:13:18
不适合我...这让我疯狂...这是冲洗我的观念.. – 2013-04-10 10:24:36
呃,不知道你为什么使用你的代码中有大量的'::',那就是C++,而且根本不是有效的C语法。另外[应该没有'malloc()'的返回值的转换,在C]中(http://stackoverflow.com/a/605858/28169)。 – unwind 2013-04-10 10:29:09