skip to Main Content

Can I initialize a stuct in C in the following way:

struct database {
  char* Name;
  char* Title;
  char* DOB;
  int EmployeeNo;
} people[100];

people[0] = { "Jon", "Manager", "1-1-1990", 12345 };
people[1] = { "Bob", "Accountant", "1-1-1990", 54321 };

I am using gcc version 9.2.1 20191130 (Debian 9.2.1-21)

3

Answers


  1. No, do it like this:

    struct database {
        char* Name;
        char* Title;
        char* DOB;
        int EmployeeNo;
    };
    
    struct database ppl[5] = {
        { .Name = "Jon",  .Title = "Manager", .DOB = "1-1-1990", .EmployeeNo = 12345 },
        { .Name = "Ravi", .Title = "Manager", .DOB = "1-1-1990", .EmployeeNo = 12345 },
        {.....},
        {.....},
        {.....},
    };
    

    Initialization and definition must be done at the same time — otherwise, you’re assigning, not initializing.

    Login or Signup to reply.
  2. No, the correct way is:

    struct database {
      char* Name;
      char* Title;
      char* DOB;
      int EmployeeNo;
    } people[100]={ { "Jon", "Manager", "1-1-1990", 12345 },
                    { "Bob", "Accountant", "1-1-1990", 54321 }
                  };
    

    This is usable in C89, C90, C94, C99, C11, C17 — and pre-standard C if the initialization is done at file scope.

    Login or Signup to reply.
  3. Can I initialize a stuct in C in the following way:

    Not quite.
    There are other ways to initialize as provided by other answers.
    You can assign within a function with a compound literal.

    people[0] = 
        (struct database){ "Jon", "Manager", "1-1-1990", 12345 };
    people[1] = 
        (struct database){ "Bob", "Accountant", "1-1-1990", 54321 };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search