Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C Programming (http://www.velocityreviews.com/forums/f42-c-programming.html)
-   -   Is compiler always takes care of adding '\0' in character arrayinitialization ? (http://www.velocityreviews.com/forums/t741760-is-compiler-always-takes-care-of-adding-0-in-character-arrayinitialization.html)

Shivanand Kadwadkar 01-09-2011 06:06 PM

Is compiler always takes care of adding '\0' in character arrayinitialization ?
 
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?
---------------------------------------------------------------------------------

Eric Sosman 01-09-2011 07:34 PM

Re: Is compiler always takes care of adding '\0' in character arrayinitialization ?
 
On 1/9/2011 1:36 PM, christian.bau wrote:
> [...]
> 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."

--
Eric Sosman
esosman@ieee-dot-org.invalid


All times are GMT. The time now is 12:45 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.