In C, how do I "directly" copy a struct to an array member?

Viewed 36

So I want to do this:

struct element{
  int t;
};

int main(int argc, char *argv[]) {
  struct element arr[10];
  arr[0]={3};
  return 0;
}

But this gives me the following error:

test.c: In function ‘main’:
test.c:7:10: error: expected expression before ‘{’ token
    7 |   arr[0]={3};
      |          ^

To fix this, I will have to resort to writing:

int main(int argc, char *argv[]) {
  struct element arr[10];
  struct element tmp = {3};
  arr[0]= tmp;
  return 0;
}

But I think it is inelegant to write a tmp value when I just want to assign directly to element{3}. How do I fix the syntax so that I do not need to create this tmp value?

1 Answers

What you want is a compound literal:

arr[0]=(struct element){3};
Related