Null byte and arrays in C

前端 未结 3 1466
滥情空心
滥情空心 2021-02-13 18:43

If I declare a char array of say 10 chars like so...

char letters[10];

am I creating a set of memory locations that are represented as chars fr

3条回答
  •  隐瞒了意图╮
    2021-02-13 19:19

    am I creating a set of memory locations that are represented as chars from index 0-9

    Yes

    then the 10th index is the null byte?

    No.

    You reserved space for exactly 10 chars. Nothing else. Nothing will automatically set the last byte to zero, or act as if it were. There is no 11th char that could hold a zero, you only have 10.

    If you're going to use that with string functions, it's your duty as the programmer to make sure that your string is null-terminated. (And here that means it can hold at most 9 significant characters.)

    Some common examples with initialization:

    // 10 chars exactly, not initialized - you have to take care of everything
    char arr1[10];
    // 10 chars exactly, all initialized - last 7 to zero - ok "C string"
    char arr2[10] = { 'a', 'b', 'c' };
    // three chars exactly, initialized to a, b and c - not a "C string"
    char arr3[] = { 'a', 'b', 'c' };
    // four chars exactly, initizalized to a, b, c and zero - ok "C string"
    char arr4[] = "abc";
    

提交回复
热议问题