2

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
  • 1
    BTW, struct element tmp = element{3} this is not valid C code. Though it is valid C++. Commented Oct 23, 2020 at 12:01

1 Answer 1

5

What you want is a compound literal:

arr[0]=(struct element){3};
Sign up to request clarification or add additional context in comments.

1 Comment

The number of times I've seen ludicrous blocks of code written to do this very thing because the author(s) had no idea this feature existed in C just makes me cry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.