これが私のコードです...
#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のいくつかの質問を含むいくつかのWebサイトで利用可能な方法を試しました。
コメントされた行は、目標を達成しようとして失敗しましたが、同じエラーで失敗しました。
編集以下のテクニックを試した後..
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]