-
Initializing strings
Unfortunately, being a self-taught programmer, I can't go to a teacher and get this question answered easily, so I have to rely on others.
The question is on initializing strings. There are three basic ways to do it. One way is to initialize it as a character array with specific characters and the null character (\0).
Code:
For example:
char array_hi[3]={'H', 'i', '\0'};
A second way is to initialize it as a string constant.
Code:
char array_hi[3]="Hi";
or....
char array_hi[]="Hi";
The third way is to use a character pointer and then initialize the pointer with a string constant, like
Now, my question is this. When to use which method? The first method seems rather bulky, with the second being more streamlined version of it. But, why would you use the third? Or is it just a matter of preference?
-
This
char array_hi[]="Hi";
is almost always preferred to this
char array_hi[3]="Hi";
Simply because you get the compiler to do the counting for you. In addition, you could edit the string thus
char array_hi[3]="Hit";
and it would not be a compile time error, but you lose the \0 at the end - the result of which, the array is no longer a valid string.
Use
char *ptr_hi="Hi";
When you have no intention of modifying the string, or you have some intention of making ptr_hi point elsewhere