2016-05-05 15 views
-3
#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 

struct a // linked list node 
{ 
    char* st; 
    struct a* pr; 
    struct a* nx; 
}; 

struct a* Init(char* w); 
struct a* insert(struct a* old, char* w); 

int main(void) 
{ 
    struct a** A; 
    A = (struct a**)malloc(sizeof(struct a*)); 
    A[0] = Init("HELLO"); 
    A[0] = insert(A[0], "WORLD"); 

    // I think the problem is here. 
    A = (struct a**)realloc(A, 2*sizeof(struct a*)); 
    A[1] = Init("ELLO"); 
    A[1] = insert(A[1], "ORLD"); 

    free(A); 

    return 0; 
} 

struct a* Init(char* w) 
{ 
    struct a* body = (struct a*)malloc(sizeof(struct a)); 
    struct a* tail = (struct a*)malloc(sizeof(struct a)); 

    body -> pr = NULL; 
    body -> nx = tail; 
    body -> st = w; 

    tail -> pr = body; 
    tail -> nx = NULL; 
    tail -> st = NULL; 

    return tail; 
} 

struct a* insert(struct a* old, char* w) 
{ 
    struct a* tail = (struct a*)malloc(sizeof(struct a*)); 

    old -> nx = tail; 
    old -> st = w; 
    tail -> pr = old; 
    tail -> nx = NULL; 
    tail -> st = NULL; 

    return tail; 
} 

(私は私のコードを簡略)
私は2次元構造の配列を構築しますが、このコードは、私にセグメンテーションフォールトをエラーを与え続けています。reallocの2次元構造体配列

ここに問題があると思います。

A = (struct a**)realloc(A, 2*sizeof(struct a*)); 

しかし、なぜそれが間違っているのかわかりません。 いいですか?

ありがとうございます。

+2

コンパイルエラー: 'prog.cの:機能で '初期化': prog.cの:43:10:エラー: 'WR' 尾という名前のメンバがありません 'ストラクト' - > WR = NULLを、' – MikeCAT

+0

@ MikeCATは申し訳ありません。元のコードを改訂して以来、私は間違っていました。私は –

+0

を@BLUEPIXYと修正したかもしれません。A =(struct a **)realloc(A、2 * sizeof(struct a *)); –

答えて

1

insert()機能では、その大きさは、典型的な環境内の1つのポインタのサイズよりも大きくなるのでstruct aは、3つのポインタを持って、この行一方

struct a* tail = (struct a*)malloc(sizeof(struct a*)); 

で一つだけのポインタのための部屋を割り当てられました。

したがって、範囲外のアクセスが発生します。 Init()の機能と同じようにsizeof(struct a)を割り当てるようにしてください。

関連する問題