Gary wrote:
> When you declare an array of chars and store a string in it,
> where is the position of the null character \0?
Wherever you ask it to be, if you ask there to be one.
> And what happens to the unused memory locations?
Uninitialised elements of a struct or array object will
be 'zero initialised'.
> #include <stdio.h>
> int main(void)
> {
> char gstring2[25] = "dudes";
Same as...
char gstring2[25] =
{ 'd', 'u', 'd', 'e', 's',
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
> gstring2[5] = 'a';
> printf("%s \n", gstring2);
> return 0;
> }
>
> The output of main function was
>
> dudesa
>
> How come this code works, and the statement
> gstring2[5] = 'a';
> doesn't overwrite the null character?
It does overwrite the null character, which was followed by
another one.
You need to be careful though of situations like...
char foo[5] = "dudes";
C, unlike C++, allows such an initialisation. There is no
terminating null stored as there is no room for it.
--
Peter


|