如何通过在 C++ 中传递 [] 中的变量来定义数组的大小

How to define size of an array by passing a variable in [] in C++?

本文关键字:变量 定义 数组 何通过 C++      更新时间:2023-10-16

我的代码如下。我想声明一个大小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++ 的向量更适合这种情况,否则我们需要为它动态分配内存。