I've got a question about initializing char pointers vs other data type pointers. Specifically, we are allowed to initialize char pointers as follows:
char *char_ptr = "Hello World";
As far as I know, the only thing special about a string is that it is a '0' terminated character array. However, we are not allowed to do the following:
int *int_ptr = {1,2,3,4};
but we must do this:
int int_arr[] = {1,2,3,4};
int_ptr = int_arr;
in order to let int_ptr point to the first element of int_array.
In the char case, we have not explicitly defined the string "Hello World" as a char array before letting char_ptr point to the string, but have initialized the char_ptr directly using the string "Hello World".
My question is, why is this the case, what is special about strings that allows us to do this but can't do so with other types?
Thanks in advance,
Sriram
You can do the same in C99 or later for other types using compund literals:
#include <stdio.h>
int main(void) {
int *ptr = (int[]){ 1, 2, 3, 4 };
for(int i = 0; i < 4; ++i) {
printf("%d: %d\n",i, ptr[i]);
}
return 0;
}
The compound literal (int[]){ 1, 2, 3, 4 }
creates an unnamed int[4]
, just like "Hello"
creates an unnamed char[6]
.
So as of C99, char
is only special in providing a more convenient syntax.
The answer is:
Strings(literals) are treated as special.
Believe it! Accept it, and Live with it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With