2

In C language if

char *ptr1 = "something";

is allowed, then why not

int *ptr2 = {1,2,3};

not allowed?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Chandu
  • 43
  • 4
  • 1
    It's the way the language is designed. But admittedly this would be a useful feature of the language. – Jabberwocky Jun 26 '20 at 07:20
  • Simply put, a string literal is an array object, while `{1,2,3}` is just an initializer list. You can point to the first object of an array, but you can't point at an initializer list. – Lundin Jun 26 '20 at 08:21

1 Answers1

4

In the first case,

 char *ptr1 = "something";

"something" boils down to a pointer to the first element, of the string literal, yields a type char*, so the type is compatible and assignment in the initialization is valid.

On the other hand,

int *ptr2 = {1,2,3};

{1,2,3} is a brace enclosed initializer list, not an int *, so it's invalid operation and not allowed.

What you can do, actually is to use a compound literal for the intialization, something like

int *ptr2 = (int []){1,2,3};

where ptr2 will point to the first element of the array composed of the values given in the brace enclosed initializer list.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 7
    But watch out for the lifetime of the array: "If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block." – rici Jun 26 '20 at 07:30
  • @rici true that. I considered OP was more concerned about the syntax and that's what I tried addressing in the answer. A very welcome comment, nonetheless. – Sourav Ghosh Jun 26 '20 at 08:11