2

I'm learning C and I am confused about this stuct I came across, but I think maybe it is short hand for simply creating a struct array.

struct myStruct
{
    char *name;
    int id;
} myList[] = {
  {"bob", 1},
  {"joe", 2}
};

Is the same as

struct myStruct
{
    char *name;
    int id;
};
struct myStruct myList[]  = {
  {"bob", 1},
  {"joe", 2}
};

Or am I wrong?

11
  • 2
    Isn't ("bob", 1) identical to 1? Otherwise, yes, it's equivalent. But don't forget the semicolon after the struct definition. Commented Apr 4, 2016 at 18:56
  • For me it doesn't compile on gcc with -std=c11 flag. This doesn't seem to be standard C. Commented Apr 4, 2016 at 18:57
  • 2
    It's most likely {"bob", 1}, not ("bob", 1). Commented Apr 4, 2016 at 18:58
  • Yes sorry, typed this up with wrong brackets. Commented Apr 4, 2016 at 18:59
  • At first I thought this code won't compile because it is assigning const char* to char* , but it did. I am confused now Commented Apr 4, 2016 at 19:04

2 Answers 2

2

Yes, it is the same. The first syntax is useful in situations when you would like to keep the type of your struct anonymous:

struct {
    char *name;
    int id;
} myList[] = {
    {"bob", 1},
    {"joe", 2}
};
Sign up to request clarification or add additional context in comments.

2 Comments

Why would I want to do that?
@BarryBones41 Sometimes you just don't need a tag name for your struct - for example, when you never declare the same struct in any other place, and the struct itself is local to a file (i.e. static) or local to a function in which it is declared.
2

Yes. They are same. It is similar to

int i = 1;  

and

int i;
i = 1;

Comments

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.