c - 复制结构时出现段错误

标签 c segmentation-fault malloc memcpy

我有一个结构如下:

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/

相关文章:

c++ - 尝试访问指针内的数组时出现段错误

c - 指针 - 转换为结构指针 + Malloc

c - 使用 Str(n)cat 的 Pebble 堆损坏

C - strlen ("288_882_288"+strlen ("288_882_288")/2 = 6?

c++ - 如何在删除类指针列表时删除段错误

c 的自定义 malloc 函数

c - 使用 malloc 获取模拟数组的大小

c - 输出到文件c编程

c - 当 x 不在其范围内时,为什么此语句要设置 x 的值?

python - Blender:分段,故障核心转储?