If a char
array is uninitialized, are all the array elements automatically initialized as 0
?
I was solving the problem Holes and my first solution which got WA was this : http://ideone.com/Ix4kc9
I then checked someone else’s solution which was almost identical but instead of for (z = 0; c[z] != '0'; ++z)
, he had used for (z = 0; c[z] != '\0'; ++z)
. After some googling I found that \0
is NULL character. I don’t understand what it actually is. Then I found this question on SO. The top answer says that all uninitialized elements are stored as zeroes. Then why replacing for (z = 0; c[z] != '0'; ++z)
with for (z = 0; c[z] != '\0'; ++z)
gave me an AC?
Uninitialized spaces are filled as zeroes. But, that means, integer zero, or the character whose ASCII value is zero (which, in fact, is '\0'
). I believe, you already know that characters are represented by their ASCII codes. So, the character '\0'
has an ASCII value of 0
, while the character '0'
has an ASCII value of 48
.
'\0'
is a special character used to terminate strings in C/C++. That is, the end of a string is marked by a '\0'
(which, again I am repeating, is the character, whose ASCII value is zero). So, that explains the for loop.
And, when they say zero filles, it is actually meant as filled with the NULL character or the character whose ASCII value is zero.
1 Like
@tijoforyou Nice explanation. Thank you.
And yes, I knew that characters are represented by their ASCII values.