C language basics(1): initalization of objects

There are two sorts of initialization:

  • at compiler time
    • The object with static duration: global variables, marked as static, extern, can only be initialized at compile time.
    • compile-time initialization can only be done using constant expressions.
  • at run time.
    • Any other object has automatic duration, and can only be initialized at run time.
    • can be done using any expressions.

“all or nothing” approach (to aggregate initializations): an attempt to explicitly initialize any part of the aggregate, will guarantee that the entire aggregate be initialized. The parts without an explicit initializer will be zero-initialized:

pointer: NULL.

Arithmetic type: positive zero. (for character type, c = 0 equals to c = ‘\0’) ‘\0’ is to emphasize the character nature of some expression.

Aggregate: every member is initialized based on its type.

Union: the first name number is initialized based on its type.

 

This rule explains this fact: “When you initialize a character array with a string, the system adds ‘\0’ to the end of the string, by default.”

If you define char str[4] = “123”, the compiler initializes str[3] to zero.

If you define char str[4] = “1234”, str[3] is ‘4’, and there is no ending ‘\0’.

If you define char str[4] = “12345”, the compiler will warn that “initializer-string for array of chars is too long”. The interesting facts are: strlen(str) is 5, sizeof(str) is 4, when you use printf(“%s”, str), it prints “1234”, without “5”.

But I don’t understand why 5 is still not there, even I print the chars one by one, printf(“%c”, str[4]) is nothing….

If I define char str[2][4] = {“12345”}, the compiler warns, strlen(str[0]) is 4, sizeof(str) is 8. Printf(“%s#%s”, str[0], sre[1]) will give you “1234#”.

If I define char str[2][4] = {“12345”, “123”}, warning, strlen(str[0]) = 7, sizeof(str) is 8. Printf(“%s#%s”, stre[9], str[1]) will give you “1234123#123);

String_5[2][4] = {“1234”};

String_5[1] is initialized the same as objects that have static storage duration.

References:

http://publications.gbdirect.co.uk/c_book/chapter6/initialization.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s