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 回答