C character arrays

Why is this character array 8 characters long:

char CharArrayVar[] = {'J', 'o', 'h', 'n'};

But this character array is 4 characters long:

char CharArrayASCIIVar[] = {74, 111, 104, 110};

This code


1
2
printf("strlen(CharArrayVar) = %d\n", strlen(CharArrayVar));
printf("strlen(CharArrayASCIIVar) = %d\n", strlen(CharArrayASCIIVar)); 


Produces this result:

strlen(CharArrayVar) = 8
strlen(CharArrayASCIIVar) = 4






Last edited on
Pure chance. Neither array is null-terminated, so strlen reads beyond array bounds in both cases.
You probably meant to use sizeof.
I didn't realize that character arrays had an indeterminate array size when initialized with individual characters.

I ran into problems using strlen as part of a for-loop condition:

1
2
3
4
for (i = 0; i < strlen(CharArrayVar); i++){ 

    printf("%c", CharArrayVar[i]);
}

I assumed that the character array had been null-terminated, but according to the above article, only character arrays initialized with double-quoted strings are.

Thus, the solution is to manually add the null-terminator:

char CharArrayVar[] = {'J', 'o', 'h', 'n', '\0'};

Now my strlen condition works just fine.
Last edited on
I didn't realize that character arrays had an indeterminate array size when initialized with individual characters.

Well, they don't. The array size is 4 in both cases.
@Athar
You should explain that you are picking at his terminology.

@df
Arrays always have a definite size, known to the compiler.

However, a 'string' may have an indeterminate size.
Last edited on
Topic archived. No new replies allowed.