1

I tried to initialize struct variable as following:

struct Abc{
    char str[10];
};

int main(){
    struct Abc s1;
    s1.str="Hello";  //error
}

I can understand this behavior because it is same as

char str[10];
str="Hello"; // incompatible types

But look at following initializations

struct Abc s1={"Hello"};   //This is fine

struct Abc s2={.str="Hello"};  //This is also fine

I remember in my graduation, I read lot of text books which said these both initializations are one and same thing (i.e initialing struct variables using { } notation and explicitly using (.) operator are same thing ). But above discussion proves that they are not same.

My question is what exactly is difference between these initializations?

A.s. Bhullar
  • 2,680
  • 2
  • 26
  • 32

3 Answers3

7

The difference is, these two lines

struct Abc s1={"Hello"};   //This is fine
struct Abc s2={.str="Hello"};  //This is also fine

are initialization, while this

s1.str="Hello";

is assignment. You can initialize a char array to a string literal, but not through assignment.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
3

Thisstruct Abc s2={.str="Hello"}; can be called as designated initialization, whereas struct Abc s1={"Hello"};general initialization.

Let me explain the advantage of this designated initialization with example.

Assume structure is having variable like struct ex{ char *name; int age; char *city; char *country } . In this if you want initialize only city&country designated initialization can be used. But in case of general initialization each members needs to be initialized separately. This this overhead for the programmer&complex also.

mahendiran.b
  • 1,315
  • 7
  • 13
2

The following assignment statements are exactly same (but wrong):

s1.str="Hello"; & str = "Hello";.

The difference is just that first one is a string inside a struct.

And by the way, initialization means assigning value to a variable at the time of its definition.

struct Abc s1; declares and defines s1 so you initialize it here as:

struct Abc s1={"Hello"};   //This is fine
struct Abc s2={.str="Hello"};  //This is also fine 

Doing this

struct Abc s1;
s1.str="Hello";

is not a initialization, it is just assigning constant string literal to str pointer which is incompatible.

0xF1
  • 6,046
  • 2
  • 27
  • 50