Niranjan Kotha Niranjan Kotha - 1 month ago 7
C Question

whats the difference between inclusion of null character and exclusion in character array?

What's the difference between the following two character arrays: one with a null character and one without a null character?

char name1[] = {'j','o','h','n'};
char name2[] = {'j','o','h','n','\0'};


If there is a difference between
name1
and
name2
how does
strlen
work on
name1
since it has no null character?

What would the result be for

printf("%d", name1[5] == '\0');


I expected it to be 0 but got 1

Answer

how does strlen work on name1 since it has no null character.

It doesn't. This would invoke undefined behaviour.

I expected it to be 0 but got 1

Your code snippet tries to access name1[5]. Given that name is a char array of size 4, you are accessing memory that has nothing to do with that array. Possibly at the time of execution that memory happened to contain a null character, leading to this result. This cannot be predicted however, and so the behaviour is undefined.