C如何将struct分配给struct?

问题描述 投票:2回答:1

下面的代码给我一个编译错误“incompatible types at assignment

档案1:

struct x{ 
  int a; 
  int b; 
  int c;
};

文件2:

static struct x d;
void copyStructVal(){
  d-> a = 1;
  d-> b = 2;
  d-> c = 3;
}
x getStruct(){
 copyStructVal();
 return d;
}

档案3:

static struct x e;
void copy(){
 e = getStruct();
}

我搜索过这个并找不到答案。我可以使用指针吗? (我是C的业余爱好者)

c struct
1个回答
4
投票

在C中,你需要在结构名称后写struct,除非你typedef它。换一种说法:

x getStruct(){

一定是:

struct x getStruct(){

既然你在其余的代码中写了它,我想这是一个错字。

最重要的是,你必须修复这3行,因为d不是指针:

  d-> a = 1;
  d-> b = 2;
  d-> c = 3;

他们应该是:

  d.a = 1;
  d.b = 2;
  d.c = 3;
© www.soinside.com 2019 - 2024. All rights reserved.