tags:

views:

132

answers:

5

Neither of these snippets of code work:

int main() {
    struct mystruct {
        int a;
        char* b;
        char* c;
    } e,f;
    e = {5, "blaat", "boe"};

    return 0;
}

Error: syntax error for '{' token

int main() {
    struct mystruct {
        int a;
        char* b;
        char* c;
    } e,f;
    struct mystruct e = {5, "blaat", "boe"};

    return 0;
}

Error: previous declaration of 'e' was here

What is the correct way to do this?

+2  A: 
int main() {
    struct mystruct {
        int a;
        char* b;
        char* c;
    } f;
    struct mystruct e = {5, "blaat", "boe"};

    return 0;
}
anon
+1  A: 

Either initialize the members in one go like the following:

int main() {
struct mystruct {
    int a;
    char* b;
    char* c;
} f;
  struct mystruct e = {5, "blaat", "boe"};

  return 0;
}    

or assign values to them later like the following:

int main() {
 struct mystruct {
    int a;
    char* b;
    char* c;
 }e,f;

 /* a,b,c are initialized with unknown values */

   e.a=5; /*Assignment instead of initialization*/
   e.b="blaat";
   e.c="boe";

   return 0;
 }
Prasoon Saurav
A: 

This works:

int main() {
    struct mystruct {
        int a;
        char* b;
        char* c;
    } e = {5, "blaat", "boe"}, f;

    return 0;
}
fortran
+1  A: 
e = {5, "blaat", "boe"};

This can only be done during initialisation and since you've already initialised 'e' as part of your struct declaration, you can't follow up with it. I recommend Neil's method.

acron
With C99 this is no longer so, but the given syntax is wrong: struct mystruct e; ... e = (struct mystruct){5, "blah", "boe"};This assigns e to a "compound literal", and uses the implicit assignment created for all structs (which is translated into something similar to an inline memcopy() call).
Tim Schaeffer
I did not know that! :)
acron
+2  A: 

Compound literal assignment is new with C99, and the syntax would be

e = (struct mystruct) {5, "blaat", "boe"};

The cast expression is required.

In C89, you either have to initialize e as part of the declaration:

struct mystruct {int a; char *b; char *c} e = {5, "blaat", "boe"};

or

struct mystruct e = {5, "blaat", "boe"};

or you have to assign members individually:

struct mystruct e;
e.a = 5;
e.b = "blaat";
e.c = "boe";
John Bode