简体   繁体   中英

Is this End of Transmission character or something else?

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?

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 .


Might Interest you

访问数组边界之外是未定义的行为

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM