Approaches to declare and/or initialize a char array in C

August 15, 2017
char str[];   

Error denoted by IDE:
Local incomplete array must be initialized

char str[100];  

OK

char str[] = "hahaha";  

OK

char str[100] = "hahaha";

OK

char str[3] = "hahaha";  

Error denoted by IDE:
initializer-string for array of chars is too long

char str[] = {'h','e','l','l','o'};  

OK

char str[100] = {'h','e','l','l','o'};  

OK

char str[3] = {'h','e','l','l','o'};  

Error denoted by IDE

char str[3] = {};  

OK

char *c = "hahaha";

Warning in compiling:
warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

char *c = {'a', 'b'}; 

Error in compiling:
error: scalar object 'c' requires one element in initializer

Extra Notes:
According to my experience in the proxy lab of course 15-213, declaring an pointer like char *cp and using it to store string is extremely unsafe. Since there is no extra space allocated for this pointer. Any assignments that exceeds the length of a pointer will overwrite following contents in the stack.

There are at least two typical approaches to store a char array that in a rather safer manner.

  • Declare a char array which is large enough to hold the string to be stored:
#define LINE_MAX 8194;  
char str[LINE_MAX];
  • Declare a pointer to char, and use malloc to allocate memory for it. This approach is recommended but a bit more complex than the first approach:
#define LINE_MAX 8194;
char *cp;
cp = (char *) malloc(sizeof(char) * LINE_MAX);
...
free(cp);

Updated on 8/18/2017:

Extra Instances of Declaring char arrays:

char str[5]={"abc"};

is legal. It is automatically translated into:

char str[5]={'a', 'b', 'c', '\0', '\0'};

It should be noted that even though the characters after 'c' have value 0, it is actually initialized to 0 rather than left unintialized.

sizeof(str) equals 5

Also,

char str[]={"abc"};

is legal. It is equivalent to:

char str[]={'a', 'b', 'c', '\0'};

sizeof(str) equals 4