我有一个结构如下:
extern struct team_t
{
char *name1;
char *email1;
char *name2;
char *email2;
} team;
struct team_t team =
{
"some string1",
"some string2",
"some string3",
"some string4"
};
然后在另一个文件中创建以下函数,将该结构复制到新结构中:
void *ucase( struct team_t *team)
{
struct team_t *ucase_team = malloc( sizeof *ucase_team);
memcpy ((char*)ucase_team, (char *)team, sizeof (ucase_team));
return NULL;
}
但是,当我想调用 ucase(team)
时,我遇到了段错误。我需要使用 void *
因为这稍后将用于 shell 信号。我错过了什么?
更新:以下调用给出一元“*”类型参数(具有“struct team_t”)
错误:
ucase(*team)
更新 2:我已删除 Null 返回并使用 ucase(team)
但仍然出现段错误。
最佳答案
memcpy()
的最后一个参数应该是 sizeof(struct team_t)
而不是 sizeof (ucase_team)
作为 ucase_team
是一个结构体指针变量。它可以是 sizeof(*ucase_team)
或 sizeof(struct team_t)
。
还调用team()
函数,例如
ucase(*team);
是错误的,因为team
不是指针类型的变量,它是一个普通的结构变量。也许你想要
ucase(&团队)
;
关于c - 复制结构时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52314787/