简体   繁体   English

初始化器值太多; 初始化动态分配的数组?

[英]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.最近在学习 C++ 时,我为一个数组动态分配了空间,并尝试在下一行用 8 个默认值初始化它。

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" Visual Studio 不喜欢那样,并用红色下划线2 ,好像那里有问题,只是给我错误“初始化值太多”

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.好吧,这似乎也不适用于常规的非指针数组,我一定只是在做一些愚蠢的事情。

intArray is not an array, it's a pointer. intArray不是数组,而是指针。 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: C 数组也可以在声明处初始化:

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

C++ allows static allocation without dimension parameter C++ 允许没有维度参数的静态分配

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.必须传递匹配的维度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM