Is compiler always takes care of adding '\0' in character arrayinitialization ?

  • Thread starter Shivanand Kadwadkar
  • Start date
S

Shivanand Kadwadkar

I was trying to test what is the output of program if i dont reserve
any space for '\0' in the character array that i have declared.
---------------------------------------------------------------------------------
#include<stdio.h>

int main()
{

char var1='A',var2[2]="BC",var3='E';

printf("\n var1=%c var2=%s var3=%c and sizeof(var2)=
%d",var1,var2,var3,sizeof(var2));

return 0;
}



output:
var1=A var2=BC var3=E and sizeof(var2)=2

in memory they are allocated in following way:
FFF5 : A
FFF4 : // i havent checked what is here ? assumed it is \0
FFF3 :C
FFF2 :B
FFF1 : E

my question here is, is compiler implicitly reserves a byte for '\0'
when we dont reserve any space for '\0' as the case with var2 always?
---------------------------------------------------------------------------------
 
E

Eric Sosman

[...]
If your array has a size big enough for the characters and a '\0' plus
possibly more characters, '\0' is added.

char a [4] = "ABC";
char a [10000] = "ABC"; // First four chars are 'A', 'B', 'C' and
'\0'.

The array will hold 'A', 'B', 'C', and 9997 '\0' chars. Loosely
speaking, if any part of an array is initialized, the entire array is
initialized. Unmentioned elements -- in this case, the final 9996 --
receive "zeroes of the appropriate kind."
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top