Edmund's blog

Writing code.

Character pointer versus array

What is the difference between const char * and const char []?

Let’s run some code to see.

1
2
3
4
5
const char str1[] = "Hello";
size_t len1 = sizeof(str1));  // -> 6

const char *str2 = "Hello";
size_t len2 = sizeof(str2));  // -> 8 (BAD!)

The first one returns the actual size of the string, which is 6 characters including the null terminator. The second one returns the size of a pointer, 8 bytes or 64 bits.

The second notation throws away information. Strings should always be declared as arrays so that their size is known.