How can char
pointer be initialized with a string (Array of characters) but an int
pointer not with a array of integer?
When I tried this
int* a={1,2,3,4,5};
It gives an error saying
error: scalar object ‘a’ requires one element in initializer
But,
char* name="mikhil"
works perfectly.
Because these are the rules (standards) of the language. There's nothing telling you it's possible to initialize a pointer with an array like this, for example, the following is also illegal:
char* name={'m', 'i', 'k', 'h', 'i', 'l', 0};
A literal string gets its own treatment and is not defined just as an array of characters.
In case of you're trying to initialize an int *
with
{1,2,3,4,5};
it is wrong because {1,2,3,4,5};
, as-is, is not an array of integers. It is a brace enclosed list of initializer. This can be used to initialize an int
array (individual elements of the array, to be specific), but not a pointer. An array is not a pointer and vice-versa.
However, you can make use of a compound literal to initialize an int *
, like
int * a = (int []){1,2,3,4,5};
For convenience, the language allows char * (or, preferably, const char *) to be initialized with a string. This is because it is a very common usage, and it has been possible since C. You shouldn't really modify the string value (of course, that's a separate debate).
With an int, if you initialize an int a[5], it is expected you might change the values. The initialized values will be copied into your array (compiler optimizations not withstanding), and you can change them how you see fit. If int *a was allowed to initialize this way, what would it be pointing to? It isn't really clear, so the standard doesn't allow 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