What is the difference between single quoted and double quoted declaration of char array?
In C, when a character array is initialized with a double-quoted string and the array size is not specified, the compiler automatically allocates one extra space for string terminator β\0β.
Example
The below example demonstrates the initialization of a char array with a double-quoted string without specifying the size. The below program prints 6 as output.
C
// C program to demonstrate the initialization of a char // array with a double quoted string without specifying the // size. #include <stdio.h> int main() { // size of arr[] is 6 as it is '\0' terminated char arr[] = "Beginner" ; printf ( "%lu" , sizeof (arr)); return 0; } |
6
On the other hand, when the character array is initialized with comma comma-separated list of characters and the array size is not specified, the compiler doesnβt create extra space for the string terminator β\0β.
Example
The below example demonstrates the initialization of a char array with comma separated list of characters without specifying the size of the array.
C
// C program to demonstrates the initialization of a char // array with comma separated list of characters without // specifying size of array. #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; } |
5
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.