What is the difference between single quoted and double quoted declaration of char array?

In C/C++, when a character array is initialized with a double quoted string and array size is not specified, compiler automatically allocates one extra space for string terminator ‘\0’. For example, following program prints 6 as output.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<stdio.h>
int main()
{
  // size of arr[] is 6 as it is '\0' terminated 
  char arr[] = "geeks";
  
  printf("%lu", sizeof(arr));
  
  return 0;
}

chevron_right


Output :

6

If array size is specified as 5 in the above program then the program works without any warning/error and prints 5 in C, but causes compilation error in C++.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Works in C, but compilation error in C++
#include<stdio.h>
int main()
{
  // arr[] is not terminated with '\0'
  // and its size is 5
  char arr[5] = "geeks"
    
  printf("%lu", sizeof(arr));
    
  return 0;
}

chevron_right


Output :

5

When character array is initialized with comma separated list of characters and array size is not specified, compiler doesn’t create extra space for string terminator ‘\0’. For example, following program prints 5.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<stdio.h>
int main()
{
  // arr[] is not terminated with '\0' 
  // and its size is 5 
  char arr[]= {'g', 'e', 'e', 'k', 's'}; 
  
  printf("%lu", sizeof(arr));
  
  return 0;
}

chevron_right


Output :

5

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


13


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.