Reputation: 7329
So I'm doing a string basics tutorial in standard C.
I have:
char mystring[] = "HAL";
for (int i = 0; i < 3; i++)
mystring[i] += 1;
for (int k = 0; k < 10; k++)
printf("\n %d", mystring[k]);
which outputs:
73
66
77
0
4
0
0
0
0
0
Now mystring[3] = 0 makes sense to me because I read that string literals terminate in a null character so the number of bytes is n+1 chars. I have no idea why mystring[4] = 4 though. I looked 4 up in an ascii table and it says it's "end of transmission". I did a few quick google searches on end of transmission character for C strings and didn't find anything. So would somebody tell me what's going on here please? Is this a standard thing? When exactly can I expect it to happen?
Upvotes: 2
Views: 1328
Reputation: 34585
This line allocates 4 bytes of memory. The 3 that are in the array below plus the unseen string terminator '\0'
char mystring[] = "HAL";
Array indexing is from 0
, so mystring[2]
is 'L'
and mystring[3]
is '\0'
.
Indexing any further is undefined behaviour, so no-one can explain the value 4
which you are getting.
Upvotes: 0
Reputation: 3094
You're accessing out of bounds memory. You can't really know what's in it. There may be anything from the 4
you found, to just a 0
, a Thunder Cat or a demon may come out of your nose.
By the C Standard definition, accessing out of bounds memory is Undefined Behavior.
Upvotes: 5
Reputation: 1164
Once you get past the first \0, C does not define the contents of the buffer. Basically, you got whatever was left in memory from last time that area of memory was used, and it has no meaning within your context.
Upvotes: 2