3

これが私のコードです...

#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]
4

4 に答える 4

9

初期化されていないポインターを逆参照しています。

最初に のインスタンスを割り当てる必要がありますstruct one:

a = malloc(sizeof *a);

次に、メンバーを初期化できますb

a->b = malloc(sizeof *a->b);

そして、あなたはアクセスすることができますr

a->b->r = 10;

コードを my answer に適合させることにより、これが実用的なソリューションです。

于 2013-04-10T10:10:44.760 に答える
0

2 番目の逆参照のポインターであるため、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;
于 2013-04-10T10:09:42.050 に答える
-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;
于 2013-04-10T10:15:14.357 に答える