c++ 如何改变数组下标 菜鸟求救~

来源:百度知道 编辑:UC知道 时间:2024/05/27 07:34:30
我想动态改变数组下标 (就是改变BUF_SIZE 的值)
程序如下:
#include<iostream>
using namespace std;
int main()
{

int BUF_SIZE = 6;
BUF_SIZE = 5;
int a[BUF_SIZE] = { 1,2,3,4,5 };
for (int i = 0;i < BUF_SIZE;i++)
cout<<a[i]<<endl;
return 0;

}

报错:
e:\projects\pro_2\pro_2\a.cpp(12) : error C2057: expected constant expression
e:\projects\pro_2\pro_2\a.cpp(12) : error C2466: cannot allocate an array of constant size 0

之后我换了种写法:

#include<iostream>
using namespace std;
# define BUF_SIZE 7

int main()
{

BUF_SIZE= 5;
int a[BUF_SIZE] = { 1,2,3,4,5 };
for (int i = 0;i < BUF_SIZE;i++)
cout<<a[i]<<endl;
return 0;

}

仍报错:
e:\projects\pro_2\pro_2\a.cpp(10) : error C2106: '=' : left operand must be l-valu

数组定义中, 其大小必须为常量, 有两种办法,
将BUF_SIZE定义为宏, 或定义为const int BUF_SIZE;

LZ基础太差劲了.

///////////////////////////////////////////////
没办法, 如果能改变, 那还是常量么? 呵呵.

C语言, 最新的标准C99, 新添加了VLA特性, 用于支持动态数组.
但C++并不支持, 所以在数组的定义中, 大小必须为常量,
如果需要动态分配, 只能用new或malloc喽.