Search code examples
c++arrayspointersinitializationallocation

Too many initializer values; Initializing Dynamically Allocated Arrays?


Recently while going over C++, I dynamically allocated space for an array and tried to initialize it with 8 default values on the next line.

int* intArray = new int[8];
intArray = {1, 2, 3, 4, 5, 6, 7, 8};

Visual Studio didn't like that, and underlined the 2 in red, as if there is a problem there, only to give me the error "too many initializer values"

I don't know if I used incorrect syntax or if you're just not allowed to set the value of an array that way after declaration. Any ideas?

Okay, it seems this also isn't working for regular non-pointer arrays too, I must be just doing something dumb.


Solution

  • intArray is not an array, it's a pointer. A pointer can't be initialized with an initializer list.

    Dynamic allocated memory can be initialized at the moment of allocation:

    int* intArray = new int[8] {1, 2, 3, 4, 5, 6, 7, 8};
    

    C array can be initialized also at the declaration:

    int intArray[8] = {1, 2, 3, 4, 5, 6, 7, 8};