首页 > 解决方案 > 复制结构的段错误

问题描述

我有一个结构如下:

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 信号。我错过了什么?

更新:以下调用给出 type argument of unary ‘*’ (have ‘struct team_t’)错误:

ucase(*team)

更新 2:我已删除 Null 返回并使用ucase(team)但仍然出现段错误。

标签: csegmentation-faultmallocmemcpy

解决方案


的最后一个参数memcpy()应该是结构指针变量sizeof(struct team_t)而不是sizeof (ucase_team)as 。ucase_team它可以是sizeof(*ucase_team)sizeof(struct team_t)

也调用team()函数如

ucase(*team);

错误,因为team它不是指针类型的变量,而是普通的结构变量。可能你想要

ucase(&team);


推荐阅读