In addition to what others have explained, I would like to illustrate the first example a bit more in detail. As Mohit Sehgal pointed out, in C the declaration
char name[3] = "Sam";
only allocates three bytes for the variable name
, and puts no 0 string terminator: name[0] == 'S'
, name[1] == 'a'
, name[2] == 'm'
, name[3] ==
whatever is contained at the next address after that last (third) byte of name
. For example, try out the following program:
#include <stdio.h> char s[3] = "abc"; char t[] = "def"; int main(int argc, char *argv[]) { printf("s = '%s'\n", s); printf("t = '%s'\n", t); }
The result will be:
s = 'abcdef' t = 'def'
because t
has been allocated right after s
and s
now points to a string that goes on until the 0 terminator of t
is found.
If you declare an array with initialization but without dimension, enough space for all the data in the initialization list will be allocated. Therefore
#include <stdio.h> char s[] = "abc"; char t[] = "def"; int main(int argc, char *argv[]) { printf("s = '%s'\n", s); printf("t = '%s'\n", t); }
will print
s = 'abc' t = 'def'
I have tested the same declarations in C++
(using the GNU compiler), and
char name[3] = "Sam";
gives a compiler error because the string initializer (which C++ considers of length 4, including the trailing 0) is too long for the variable.
So, both in C and C++, the compiler will not allocate more bytes than are specified in the declaration.