Hir*_*dya 3 c gcc struct pointers
这是我的代码......
#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;
}
Run Code Online (Sandbox Code Playgroud)
我在这里尝试的是,将结构定义为结构.现在两个对象都应该是指针.我想设置值,r
然后显示它.
我得到它的唯一的事情Segmentation Fault
用gdb
我得到了下面的,这似乎没有帮助太多..
(gdb) run
Starting program: /home/sujal.p/structtest/main
Program received signal SIGSEGV, Segmentation fault.
0x08048435 in main ()
Run Code Online (Sandbox Code Playgroud)
我想知道如何执行上面提到的操作以及为什么这个东西会出现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;
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了所有提到的技术,他们给了我错误..我得到的最后一个错误如下..
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]
Run Code Online (Sandbox Code Playgroud)
您正在取消引用未初始化的指针.
您需要先分配一个实例struct one
:
a = malloc(sizeof *a);
Run Code Online (Sandbox Code Playgroud)
然后你可以初始化成员b
:
a->b = malloc(sizeof *a->b);
Run Code Online (Sandbox Code Playgroud)
然后你可以访问r
:
a->b->r = 10;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4370 次 |
最近记录: |