0

I am having the confusion regarding the following code snippet because for the same string the output is 1 and 2 respectively.

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
void main()
{
  char str2[1]="a",str3[]="a";
  printf("%d %d ",sizeof(str2),sizeof(str3));
  getch();
}
Jai Ho
  • 1
  • 1

3 Answers3

6
char str2[1]="a"

gives you a one-element array with content {'a'}. This array is missing the nul terminator used to denote the end of C strings so you won't be able to use str2 as a string.

str3[]="a"

gives you a char array that includes space for a nul-terminator - {'a', '\0'}

simonc
  • 41,632
  • 12
  • 85
  • 103
2

Int the first case (str2) you set the size of the array to 1; even though the initializer provided two characters, the second char is truncated to match the size of the array that you specified.

In the second case, you let the compiler pick the exact size, which in this case equals the size of the string literal.

The size of "a" is two, because you need an extra char for null terminator.

Note: in order to print size_t in a portable way you need to prefix d, u, or x with z, like this:

printf("%zd %zd ",sizeof(str2),sizeof(str3));
Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Please can you elaborate the use of the prefix z ? – Jai Ho Aug 04 '14 at 16:40
  • @JaiHo `sizeof` expression is of type `size_t`. Format specifier `%d` expects an `int`, while `size_t` is not an `int`. Although printing often goes well without `z`, as in the code I posted on the last line of the answer, there are platforms where you would end up with incorrect printout or even a crash. – Sergey Kalinichenko Aug 04 '14 at 16:43
0

String literals in C have types of character arrays that contain as many characters as explicitly specified in string literals plus the terminating zero.

For example string literal "a" consists from two characters 'a' and '\0' and have type char [2].

In this definition of array str2

char str2[1]="a";

you explicitly specified that it size equal to 1. So sizeof( str2 ) will be equal to 1 that is number_of_characters * sizeof( char )

Take into account that such definition of str2 is considered as an invalid definition in C++ because there is more initializers than initialized objects (that is elements of type char) because as I pointed out above string literals contain the terminating zero.

In this array definition

char str3[]="a";

the size of the array is not specified so it is calculated based on how many initializers are used. As string literal contains two characters ( 'a' and '\0') then str3 will be initialized with these characters and will contain two elements. That is str3 will be an exact copy of the string literal. So sizeof( str3 ) will be equal to 2.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335