Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why different char array size for identical strings in C?

In C the string is always terminated with a \0 character, so the length of the string is the number of characters + 1. So, in case you need to initialise a string of 12 characters, you must "allow one element for the termination character" (from p.221, "Beginning C", Horton).

All right, let’s try

#include <stdio.h>

int main(void)
{
    char arr1[12] = "Hello world!";
    char arr2[] = "Hello world!";
    printf("\n>%s< has %lu elements", arr1, sizeof(arr1) / sizeof(arr1[0]));
    printf("\n>%s< has %lu elements", arr2, sizeof(arr2) / sizeof(arr2[0]));
    return 0;
}

outputs

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Hello world!< has 12 elements
>Hello world!< has 13 elements

Why the C complier allowed me to create a fixed size array arr1 without a \0 character and added \0 when I asked for a variable sized array arr2?

>Solution :

When you define an array with a fixed size and initialize it with a string literal:

  • If the size is smaller than the number of characters in the string (not counting the terminating null character), the compiler will complain about the mismatch.
  • If the size equals the number of characters in the string (not counting the terminating null character), the compiler will initialize the array with the characters in the string and no terminating null character. This is used to initialize an array that will be used only as an array of characters, not as a string. (A string is a sequence of characters terminated by a null character.)
  • If the size is greater than the number of characters in the string, the compiler will initialize the array with the characters in the string and a terminating null character. Any elements in the array beyond that will also be initialized to zero.

When you define an array without a stated size and initialize it with a string literal:

  • The compiler counts the characters in the string literal, including the terminating null character, and makes that the array size.

These are the rules of the C standard.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading