serc
serc

Reputation: 83

C how to allocate struct to struct?

The following code gives me a Compile error "incompatible types at assignment"

File 1:

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

File 2:

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

File 3:

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

I've searched for this and can't find the answer. Can I do it with a Pointer? (I'm a amateur in C)

Upvotes: 2

Views: 47

Answers (1)

Acorn
Acorn

Reputation: 26194

In C, you need to write struct behind the name of a structure, unless you typedef it. In other words:

x getStruct(){

Must be:

struct x getStruct(){

Since you wrote it in the rest of the code, I guess it is a typo.

On top of that, you have to fix these 3 lines, since d is not a pointer:

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

They should be:

  d.a = 1;
  d.b = 2;
  d.c = 3;

Upvotes: 4

Related Questions