0

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.

6
  • 2
    intArray is not an array, it's a pointer. A pointer can't be initialized with an initializer list. Commented Jan 18, 2020 at 5:49
  • Try this: int* intArray = new int[8] {1, 2, 3, 4, 5, 6, 7, 8}; Commented Jan 18, 2020 at 5:54
  • Okay, that definitely works, but what about when I just declare a regular array, why can't I use an initializer list on another line there as well? Or is that a pointer too? Commented Jan 18, 2020 at 5:57
  • 1
    Your assumption is correct. Commented Jan 18, 2020 at 5:58
  • Makes much more sense now. Thanks. Commented Jan 18, 2020 at 5:59

2 Answers 2

1

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};
Sign up to request clarification or add additional context in comments.

Comments

0

C++ allows static allocation without dimension parameter

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

where for dynamic allocation

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

the matching dimension must be passed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.