Character arrays in C and pointers ofto character array are not same thing. Though you can print addresses and get same value. An array in C is made up of following things.
- Size of array
- Its address / pointer
- Homogenous Type of elements
Where a pointer is made up of just:
- Address
- Type information
char s[] = "Hello\0Hi"; printf("%d %d", strlen(s), sizeof(s));
Here you are calculating the size of array (which is s variable) using sizeof() which is 9.
But if you treat this character array as string than array(string now) looses its size information and become just a pointer to a character. Same thing happens when you try to print character array using %s.
So strlen() and %s treat character array as string and it utilize its address information only. You can guess, strlen() keep incrementing the pointer to calculate the length up-to first null character. When it encounter a null character you get a length up-to that point.
So the strlen() gives you 5 and do not count null character.
So sizeof() operator tells only the size of its operand. If you give it array variable than it utilize the array size information and tells the size regardless of null character position.
But if you give sizeof() the pointer to array of characters than it finds pointer without the size information and prints the size of pointer which is usually 64bit/8byte on 64bit systems or 32bit/4bytes on 32bit systems.
One more thing if you initialize your character arrays using double quotes like "Hello" than C adds a null character otherwise it does not in case of {'H','e','l','l','o'}.
Using gcc compiler. Hope it will help only to understand.