| Programming > C > Re: When you de... |
|
| << Topic |
< Post |
Post 8 of 9 Topic 26076 of 26972
|
Post > |
Topic >> |
Re: When you declare an array of chars and store a string in it, where is the position of the null character \0? And what happens to the unused memory locations?
by "Default User" <defaultuserbr@[EMAIL PROTECTED]
>
May 5, 2008 at 10:51 PM
|
Gary wrote:
> When you declare an array of chars and store a string in it, where is
> the position of the null character \0?
After the last character of string data.
> And what happens to the unused
> memory locations?
They are set to zero.
> #include <stdio.h>
> int main(void)
> {
> char gstring2[25] = "dudes";
> gstring2[5] = 'a';
> printf("%s \n", gstring2);
> return 0;
> }
>
> The output of main function was
>
> dudesa
You overwrote the null terminator with a character.
> How come this code works,
Because there were extra characters that were set to zero due to the
partial initialization.
> and the statement
> gstring2[5] = 'a';
> doesn't overwrite the null character?
It did, but a new terminator was in place.
If you had this:
char str[] = "dudes";
Then you'd probably be in trouble. The next adjacent byte wouldn't even
belong to your object so overwriting the null terminator would cause
undefined behavior as soon as you tried a string operation.
Brian


|
9 Posts in Topic:
|
Gary <fordgwf@[EMAIL P |
2008-05-05 15:04:29 |
|
Peter Nilsson <airia@[ |
2008-05-05 15:17:44 |
|
arnuld <sunrise@[EMAIL |
2008-05-07 08:11:13 |
|
"rio" <a@[EM |
2008-05-06 18:34:59 |
|
"Default User" |
2008-05-06 16:59:49 |
|
"rio" <a@[EM |
2008-05-06 19:31:27 |
|
"rio" <a@[EM |
2008-05-06 19:31:55 |
|
"Default User" |
2008-05-05 22:51:22 |
|
Ben Bacarisse <ben.use |
2008-05-06 18:27:35 |
|
Post A Reply:

|