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.
#include<stdio.h> int main() { // size of arr[] is 6 as it is '\0' terminated char arr[] = "geeks"; printf("%lu", sizeof(arr)); return 0; } |
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++.
// 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; } |
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.
#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; } |
Output :
5
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Difference between const char *p, char * const p and const char * const p
- What is the difference between "char a" and "char a[1]"?
- What's difference between char s[] and char *s in C?
- size of char datatype and char array in C
- C/C++ program to find the size of int, float, double and char
- C | Variable Declaration and Scope | Question 1
- C | Variable Declaration and Scope | Question 2
- C | Variable Declaration and Scope | Question 3
- C | Variable Declaration and Scope | Question 4
- C | Variable Declaration and Scope | Question 6
- C | Variable Declaration and Scope | Question 7
- C | Variable Declaration and Scope | Question 8
- What happens when a function is called before its declaration in C?
- Difference between float and double in C/C++
- What’s difference between “array” and “&array” for “int array[5]” ?
- How to execute zombie and orphan process in a single program?
- Difference between pointer to an array and array of pointers
- Double Pointer (Pointer to Pointer) in C
- Double forking to prevent Zombie process
- C program to print a string without any quote (singe or double) in the program

