[英]How to define size of an array by passing a variable in [] in C++?
My code is given below. 我的代码如下。 I want to declare an array of size
n
. 我想声明一个大小为
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
How can I declare an array of size n
in this code? 如何在此代码中声明大小为
n
的数组?
That is a declaration of a variable-length array and it's not in C++ yet. 那是一个可变长度数组的声明,还不是C ++。
Instead I suggest you use std::vector
instead: 相反,我建议您使用
std::vector
代替:
std::vector<int> array(n);
You also have other problems, like declaring a pointer but not initializing it, and then using that pointer. 您还遇到其他问题,例如声明一个指针但不初始化它,然后使用该指针。 When you declare a local variable (like
a
) then its initial value is undefined , so using that pointer (except to assign to it) leads to undefined behavior . 当您声明局部变量(如
a
)时,其初始值是不确定的 ,因此使用该指针(除了为其分配指针)会导致不确定的行为 。 In this case what will probably happen is that your program will crash. 在这种情况下,可能会发生的是您的程序将崩溃。
int *array = (int*)malloc( n * sizeof(int) );
//..
//your code
//..
//..
free(array);
You cannot declare an array of variable size in C++, but you can allocate memory once you know how much you need: 您不能在C ++中声明可变大小的数组,但是一旦知道需要多少就可以分配内存:
int* a = new int[n]; int * a =新的int [n];
//do something with your array... //对数组做点什么...
//after you are done: //完成后:
delete [] a; 删除[] a;
Since your code looks more like C... 由于您的代码看起来更像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.