数组大小声明符,可以计算吗? VC ++

时间:2015-10-27 15:53:23

标签: c++ arrays

Ubernoob问题: 在MS Visual C ++中是否可以根据用户输入声明数组大小?

int userNum;
cin >> userNum;
const int SIZE = userNum;
int myArray[SIZE];

似乎如果我以任何方式使用变量来初始化常量SIZE,那么VC ++不再将其视为常量来设置数组大小。

有解决方法吗?

4 个答案:

答案 0 :(得分:1)

没办法;-),你必须动态分配内存。有很多方法可以做到这一点(我在这里提出了3种不同的解决方案):

int userNum;
cin >> userNum;
const int SIZE = userNum;
int* myArray1 = new int[SIZE];
int* myArray2 = (int*) malloc( sizeof(int) * SIZE ); // not 100% sure about the syntax
// or, better, because memory will be released automatically for you:
std::vector<int> myArray3( SIZE ); // Thank you crashmstr for the comment

之后,当你完成后,你必须释放它:

delete [] myArray1;
free( myArray2 );
// no need to free myArray3 
// Note that statically allocated memory (int myArray[SIZE]) is automatically released

myArray[SIZE]是在编译时完成的静态分配,它不能由用户输入控制(除非用户是程序员......谁可以在程序实际编译之前改变大小; - )

建议的解决方案是使用在运行时完成的动态分配,它可以由用户输入控制。

答案 1 :(得分:1)

这可以使用std :: vector

#include <iostream>
#include <vector>


int main() {
  int userNum;
  std::cin >> userNum;
  std::vector<int> myArray(userNum);
  myArray[1]=42;
  return 0;   
}

请注意,此示例没有检查用户输入的大小。

答案 2 :(得分:1)

使用C风格的数组是一个坏主意。 首选std::vector

std::vector<int> vec(5); // Vector of 5 ints

答案 3 :(得分:0)

关于std::vector的上述答案绝对正确。

但是如果你想根据用户输入调整你的矢量大小,你可以这样做:

#include <vector>
std::vector<int> vec; 
std::cin >> userSize;
vec.resize(userSize);