[英]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 =新的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 ++的vector更适合,否则我们需要为其动态分配内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.