This question already has answers here:
Closed 3 years ago.
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.
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};
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.
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.
the language dont support null terminator to int arrays , which is since compiler would have ambiguity that is that null terminator or 0 in int array...
it is the same reason due to which
cout<<anystring;
give complete array of character i.e. complete string
and this dont
cout<<a;
for a 1-d int array a...infact it gives an error message and dont prints the complete 1-d array...
upvote if i somewhere satisfied / solved your query...