1

通常、構造体のコピーは = 演算子を使用するだけで簡単に作成でき、コンパイラーは構造体をコピーするコードを生成します。ただし、この部分では、関数は構造体へのポインターを返さなければならないので、私が試みたすべてが構造体を正しくコピーしていないことに気付いた部分にたどり着くまでずっとそれを扱ってきました。

私の問題の基本的な例は

typedef struct command_stream *command_stream_t;
command_stream_t ty = (command_stream_t) malloc(sizeof(struct command_stream));
command_stream_t yy;

do some code
//ty contains a variable words which is an array of strings

*yy = *ty;
 ty->words = NULL; //set to null to see if yy still contains a copy of the struct
 printf("%s", yy->words[0]);

ここでセグメンテーション違反が発生します。ただし、変更するとポインターではなくなります

typedef struct command_stream command_stream_t

yy=ty;
ty.words = NULL;
printf("%s", yy.words[0]);

これはうまくいきます!ポインターに対して同じことを行う方法が完全にはわかりません。また、500以上の行コードを変更したくありません...

4

2 に答える 2

3

あなたのyyポインタは決して初期化されません。

そこに構造体を保持するのに十分なメモリを割り当ててから、* を使用してコピーするかmemcpy、ポインタとサイズを使用する必要があります。

于 2013-01-18T16:53:41.280 に答える
0

このようなことを試しましたか?

struct command_stream* ty = (struct command_stream*) malloc(sizeof(struct command_stream));

/* do things with the struct */

struct command_stream ty_val = *ty;
struct command_stream yy = ty_val;
于 2013-01-18T16:57:59.233 に答える