A.s. Bhullar
A.s. Bhullar

Reputation: 2788

struct variable initialization

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?

Upvotes: 1

Views: 276

Answers (3)

mahendiran.b
mahendiran.b

Reputation: 1323

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.

Upvotes: 3

0xF1
0xF1

Reputation: 6116

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.

Upvotes: 2

Yu Hao
Yu Hao

Reputation: 122363

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.

Upvotes: 7

Related Questions