Why is the string length of buf1[12] = "hello world?" 13?

55 Views Asked by At

I have the code and output below, why are the string length of buf1 and buf2/buf3 different?

#include <stdio.h>
#include <string.h>

int main() {
    char buf1[12] = "hello world?";
    char buf2[] = "hello world?";
    char buf3[13] = "hello world?";
    int buf1length, buf2length, buf3length;

    buf1length = strlen(buf1);
    buf2length = strlen(buf2);
    buf3length = strlen(buf3);

    printf("buf1length: %d\n", buf1length);
    printf("buf2length: %d\n", buf2length);
    printf("buf3length: %d\n", buf3length);

    printf("buf1: %lu\n",sizeof(buf1));
    printf("buf2: %lu\n",sizeof(buf2));
    printf("buf3: %lu\n",sizeof(buf3));
}

Output:

buf1length: 13
buf2length: 12
buf3length: 12
buf1: 12
buf2: 13
buf3: 13

Since the strlen() function doesn’t count the null character \0, and the size of buf1 is 12,

how come is the string length of buf1[12] 13?

0

There are 0 best solutions below