指针;数组的简单分配

时间:2015-01-27 21:17:13

标签: c++

我在“int dArray [size]”下遇到错误,说大小需要是常量。有人可以解释这究竟意味着什么吗?

我希望它是一个大小为4的数组,输出1,3,5和7。

#include <iostream> 

using namespace std; 

int *AllocateArray(int size, int value){
int dArray[size];
for (int i = 0; i <= size; i++){
    dArray[i] = value;
    value + 2;
}
}

int main(){

AllocateArray(4, 1);
}

解决:

以下是最终正在运行的代码。

#include <iostream> 

 using namespace std; 

int *AllocateArray(int size, int value){
int * Array = new int[size];
for (int i = 0; i < size; i++){
    Array[i] = value;
    value = value + 2;
}
for (int i = 0; i < size; i++){
    cout << Array[i] << endl;
}
return Array;
}

int main(){

int *dArray = AllocateArray(4, 1);

}

4 个答案:

答案 0 :(得分:3)

int dArray[size]尺寸不是常数。因此,你得到了这个错误。您可能想要做的是使用指针创建一个新数组,如:

int * dArray = new int[size];

答案 1 :(得分:2)

C ++要求在编译时确定数组的大小。由于size是在运行时确定的,编译器会抱怨。

如果您对在编译时具有未知大小的类似行为的行为感兴趣,请考虑使用std::vector

答案 2 :(得分:1)

数组的大小在编译时应该是已知的常量,以便编译器可以为堆栈上的该数组分配正确的内存。请记住,这样的声明是针对堆栈变量的。如果你想要动态数组,请尝试std :: vector。

答案 3 :(得分:0)

您必须使用数字#define或const unsigned int声明数组的大小。否则它们被认为是可变长度数组。

示例:

const unsigned int MAX_ARRAY_SIZE = 14;
double my_array[MAX_ARRAY_SIZE];