如何通过在 C++ 中传递 [] 中的变量来定义数组的大小
How to define size of an array by passing a variable in [] in C++?
我的代码如下。我想声明一个大小n
数组。
FILE *fp;
fp=fopen("myfile.b", "rb");
if(fp==NULL){ fputs("file error", stderr); exit(1); }
int* a;
fread(a, 0x1, 0x4, fp);
int n=*a;
int array[n]; // here is an error
如何在此代码中声明大小为 n
的数组?
这是一个可变长度数组的声明,它还没有C++。
相反,我建议你改用std::vector
:
std::vector<int> array(n);
您还有其他问题,例如声明指针但不初始化它,然后使用该指针。当您声明一个局部变量(如 a
)时,它的初始值是未定义的,因此使用该指针(除了分配给它)会导致未定义的行为。在这种情况下,可能会发生程序崩溃的情况。
int *array = (int*)malloc( n * sizeof(int) );
//..
//your code
//..
//..
free(array);
您不能在 C++ 中声明可变大小的数组,但是一旦知道需要多少内存,就可以分配内存:
int* a = new int[n];
对你的数组做点什么...
完成后:
删除[] a;
由于您的代码看起来更像 C...
FILE *fp = fopen("myfile.b", "rb");
if(fp==NULL)
{
fputs("file error", stderr);
exit(1);
}
//fseek( fp, 0, SEEK_END ); // position at end
//long filesize = ftell(fp);// get size of file
//fseek( fp, 0, SEEK_SET ); // pos at start
int numberOfInts = 0;
fread(&numberOfInts, 1, 4, fp); // you read 4 bytes sizeof(int)=4?
int* array = malloc( numberOfInts*sizeof(int) );
数组只接受 const 对象或表达式,编译时可以由编译器决定值,来自 c++ 的向量更适合这种情况,否则我们需要为它动态分配内存。
相关文章:
- 用C++中的一个变量定义一个常量
- 变量定义到C++布尔值转换
- 未声明的标识符错误,但变量定义正确 (?)
- C++多线程程序:变量定义为类成员的隔离错误
- 将变量定义为静态时,为什么可以多次定义它
- 初始值设定项列表与构造函数赋值与变量定义
- 如何根据传递给函数的变量定义特征矩阵大小
- C++ 描述如何使用来简化变量定义
- 如何转发声明依赖于变量定义的类,而变体定义又依赖于模板化类?
- 是否修改其声明语句中的变量定义良好
- 使用类的其他成员变量定义类的成员变量数组
- 是否可以通过全局变量定义具有可变参数数的函数中的参数数量
- 元组 std::get() 不适用于变量定义的常量
- 全局使用变量定义和C 声明
- C++变量定义中的易失性类型量词位置
- 将变量定义为数组和正确的语法
- 多个,包括具有变量定义的头文件
- 调用构造函数,并将成员作为参数解析为变量定义
- 逗号分隔变量定义中关系前的序列
- 如何使用命名变量定义常量右值引用参数的默认值