whatever
whatever

Reputation: 11

Initialize each member to an empty C string

The instruction wanted me to declare a variable of type Name to be used for storing a contact’s full name, but how do I exactly initialize each member to an empty C string?

type Name header file:

struct Name {
    char firstName[31];
    char middleInitial[7];
    char lastName[36];
};

My attempt: struct Name myname = { {0} };

did I do it right?

Upvotes: 1

Views: 878

Answers (1)

chux
chux

Reputation: 153348

struct Name myname = { {0}}; is close

warning: missing initializer for field 'middleInitial' of 'struct Name' [-Wmissing-field-initializers]

{0} is sufficient. @machine_1


Alternative listed below. It depends on how expressive you want to be.

struct Name {
  char firstName[31];
  char middleInitial[7];
  char lastName[36];
};

// struct Name myname = { {0}};
struct Name myname1 = {0};
struct Name myname2 = { {0}, {0}, {0}};
struct Name myname3 = { "", "", "" };
struct Name myname4 = { .firstName = "", . middleInitial = "", .lastName = "" };
struct Name myname5 = { .firstName = "" };
struct Name myname6 = { { [0] = 0 }, "", {0}};
// many others

In C, either all of the object is initialized, or none of it, no partial initializations.

When the initialize is incomplete, the rest is fill with something, which is usually bits of zeros. Details appropriate for another question.


Note: if struct Name myname was in global space or static, it would receive a default "zero" initialization, even without an explicit initializer.

struct Name myname;
int main() {
  printf("<%s>\n", myname.firstName); // prints "<>\n"
}

Upvotes: 3

Related Questions