Why can't I initialize int* with data

In c++,

This works:
char* a="ABC";

and this also works:
char a[] ="ABC";

The first is a pointer so it can be reassigned. The second cannot be reassigned.

However;
This does not work:
int* p = {1,3,4};

But this does:
int p[] = {1,3,4};

Why can I give initial data value (in contrast to address value) to char* but not int* when both are pointers? It seems that in case of char*, the compiler automatically allocates memory and assigns the address to char* c however it does not do this with int*.

WHY>
Last edited on
This does not work: int* p = {1,3,4};
Because there is no int counterpart to the (const) string literal that Peter described here: http://www.cplusplus.com/forum/beginner/206978/
So for int you'd have to do something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int main()
{
   int* p = new int[2];
   *(p + 0) = 1;
   *(p + 1) = 2;
   *(p + 2) = 3;

   for (size_t i = 0; i < 3; ++i)
   {
       std::cout << *(p+i) << " ";
   }
   std::cout << '\n';
   delete []p;
}
Last edited on
Curly brackets { } doesn't necessarily mean it's an array. It depends on the context.

1
2
3
// None of these work.
const char* p1 = {'A', 'B', 'C', '\0'};
const int* p2 = {1, 2, 3, 4};

If you are using { } to initialize a pointer it expects another pointer of the same type.

1
2
int i = {5}; // works the same for integers
int* p = {&i};


A string literal gives you an array. Arrays implicitly decay to a pointer to the first element in the array so that is why you can assign a string literal to a char pointer.

1
2
3
// "ABC" is an array of 4 chars.
// pa points to the first element (the A) of the array.
const char* pa = "ABC";

It's the same thing that happens when you assign a local array to a pointer.

1
2
char a[] = "ABC";
char* pa = a;
Last edited on
as a little diversion, something like this
int* p = {1,3,4}; // invalid
can be easily done in C:
int* p = (int[]){1,3,4}; // valid C, invalid C++
demo: http://coliru.stacked-crooked.com/a/f62b80928c2e260e
Topic archived. No new replies allowed.