Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a char pointer be initialized with a string (Array of characters) but an int pointer not with an array of integer? [duplicate]

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.

like image 264
Mikhil Singh Avatar asked Mar 12 '16 06:03

Mikhil Singh


3 Answers

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.

like image 67
Amit Avatar answered Sep 19 '22 23:09

Amit


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};
like image 22
Sourav Ghosh Avatar answered Sep 21 '22 23:09

Sourav Ghosh


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.

like image 35
Rob L Avatar answered Sep 19 '22 23:09

Rob L