Reputation: 13
My code is given below. I want to declare an array of size 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?
Upvotes: 0
Views: 143
Reputation: 27
Array only accept const object or expressions, the value can be decided by the compiler during compiling, vector from c++ is more suitable from this case, otherwise we need to dynamically allocate memory for it.
Upvotes: 0
Reputation: 36082
Since your code looks more like 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) );
Upvotes: 0
Reputation: 12563
You cannot declare an array of variable size in C++, but you can allocate memory once you know how much you need:
int* a = new int[n];
//do something with your array...
//after you are done:
delete [] a;
Upvotes: 0
Reputation: 36
int *array = (int*)malloc( n * sizeof(int) );
//..
//your code
//..
//..
free(array);
Upvotes: 0
Reputation: 409136
That is a declaration of a variable-length array and it's not in C++ yet.
Instead I suggest you use std::vector
instead:
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. In this case what will probably happen is that your program will crash.
Upvotes: 4