-3
char txt[20] = "Hello World!\0";

How many bytes are allocated by the above definition? Considering one char occupies 1 byte, one int 2 byte. Note that there is only one ", and \0 at the end. How to calcultate many many bytes the above definition has occupied?

Andre Kampling
  • 4,867
  • 2
  • 15
  • 41
Maths Maniac
  • 83
  • 1
  • 6

2 Answers2

5

Statement char txt[20]="Hello World!\0" comprises actually two parts, a definition part and an initialization part. char txt[20], the definition part, tells the compiler to reserve 20 elements of size of character (in this case 20 bytes), regardless of the content with which you will initialize the array later on. The initialization part ="Hello World!\0" then "prefills" the reserved memory with the characters of literal Hello World!\0. Note that it is actually not necessary to write \0 explicitly in the string, since string literals are by itself terminated by the \0-character. So you should write char txt[20]="Hello World!". It is OK if the length of the string literal is smaller than the memory allocated; If the length of the string literal used for initializing exceeds the length of the array, you get at least a compiler warning.

Note, however, that if you write char txt[]="Hello World!", the length of the memory reserved will be exactly the length of the initial string literal.

Concerning array initialization, you might confer to cppreference.com. Concerning the discussion on "variable definition" versus "variable declaration", I find this SO answer very helpful.

Stephan Lechner
  • 33,675
  • 4
  • 27
  • 49
  • 1
    Don't forget the variable *definition* part. – Some programmer dude May 30 '17 at 07:00
  • Variable definition? What? @Someprogrammerdude – tilz0R May 30 '17 at 07:10
  • @tilz0R A variable need both to be *declared* and to be *defined*. A declaration tells the compiler what type the variable have, and its name. A definition is what tells the compiler to actually allocate space for the variable. Most variable declarations are also definition (like in the question), but it is possible to separate the two. – Some programmer dude May 30 '17 at 07:12
  • Ok that was misunderstanding part. My understanding of your comment was that you were trying to say that variable name requires additional memory which is in fact for sure not true. Now it is ok. – tilz0R May 30 '17 at 07:14
1

Anything which goes inside the double quotes in C is considered as string with null termination in the end. You don't have to add \0 in the end.

You can use strlen(arr)+1to get the size of char. Here +1 because strlen doesn't count null termination.

danglingpointer
  • 4,071
  • 3
  • 20
  • 36