How To Initialize A Char Array

Is it a must to specify the size of an array when u initialize it. If so Why it is important give the size?
1
2
3
4
5
char whatever[];//method 1
char whatever[]="whatever";//method 2
char whatever[size];//method 3
char whatever[size]="whatever";//method 4


what is the best and correct way to initialize an array from the above??
Last edited on
Is it a must to specify the size of an array when u initialize it.
It is a must (in C++) to specify the size of an array. You may or may not initialize it.

Why it is important give the size?

Because an array without a size don't make sense.

what is the best and correct way to initialize an array from the above??
It depends on the requirements. This char whatever[]="whatever";//method 2 is a good way because the compiler determines the size.
But some books says that it is not a good programming practice to let the compiler determine the size of an array. for example if i want to keep names in a char array it is a waste of memory to initialize it's size to a constant. because sizes of names can be different.

so in this case if i didnt give the size of the char array is it taking it's default size? What is the default value
Chathu, you could always determine the size of the array at runtime?

1
2
3
4
int size;
cout << "How big of an array?";
cin >> size;
char ch[size];


also take a look at http://www.cplusplus.com/doc/tutorial/dynamic/ if you are concerned about wasting memory.
Whoa...Thanks This Is Exactly What I Wanted...
Warning!!

C++ only allows arrays to be defined with a constant size.

georgewhere's example is valid C99, not C++. Unfortunataly some compilers blur the edges between the two languages.

If compiled with a strictly ANSI C++ compiler, the code snippet will fail to compile.
Topic archived. No new replies allowed.