Question

I have:

#include <stdio.h>
int main()
{
    char ch[] = "Hello";
    char wd[] = "World";
    char ex[] = "!";

    printf("The size of a char: %ld\n",sizeof(char));
    printf("The size of ch[]: %ld\n",sizeof(ch));
    printf("The size of ex[]: %ld\n",sizeof(ex));
    printf("The size of wd[]: %ld\n",sizeof(wd));

    return 0;
}

Which yields:

The size of a char: 1
The size of ch[]: 6
The size of ex[]: 2
The size of wd[]: 6

My question: Since the size of a char is 1 byte,why isn't the size of ch[ ]=5 bytes? Since it has 5 characters (H,e,l,l and o)
The same goes with wd[ ] and ex[ ]. What's going on here?
Sorry if this is a no-brainer,but I am novice in C.

Was it helpful?

Solution 2

In this statement:

char ch[] = "Hello";

A null terminated string literal is copied into ch. Therefore there are six characters, including the NUL terminator. Note that strlen will not count the NUL terminator.

char c[] = "Hello";
printf("%s", c);

Therefore, you should use strlen when you want the size of the string, and sizeof when you want the amount of bytes in the string. Note that in the case you have a character pointer, and not an array, it will have no size information.

char* ptr = "Hello";
sizeof(ptr); // size of a character pointer
sizeof(*ptr); // size of a char
strlen(ptr);

OTHER TIPS

Since C strings are terminated with a \0, the size of the string will always be the (apparent) length + 1.

C strings are null terminated. That is, there is an extra zero byte at the end of each of your strings.

For what it's worth, sizeof(char) is always 1.

Strings in C always have at least one character: '\0'. This character is at the end of every proper string, so while the string length may be 5 bytes in size, it actually requires 6 bytes to store the string fully.

Just try this:

char empty[] = "";
printf("size: %zu\n", sizeof empty);
printf("empty[0]: %hhd\n", empty[0]);

The minimum size of a char array would be 1 byte which would be empty i.e. contain only \0 1 null byte. c strings i.e char arrays always end in \0 (null byte) so a char array with 5 letters would be 5 letters plus the null byte equals 6 bytes. One could initialize a char array with 5 bytes which would only fit 4 letters plus the null byte.

char ch[5];

ch is 5 bytes

Reference: https://devdocs.io/c/string/byte

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top