. Advertisement .
..3..
. Advertisement .
..4..
For the problem “iso c++ forbids variable length array.” I tried to fix it, but It doesn’t work and returns the result I want. Here is my program:
#include "utilities.h"
FILE *open_file(char *filename, const char*extension, const char *access)
{
char string[MAX_STR_LEN];
FILE *strm = NULL;
if(filename[0]=='\0')
{
printf("\n INPUT FILENAME (%s) > ",access);
fgets(string,MAX_STR_LEN,stdin);
sscanf(string,"%s",filename);
printf(" FILE %s opened \n", filename);
}
int len=strlen(filename);
if( len + strlen(extension) >= MAX_STR_LEN)
{
printf("\n ERROR: String Length of %s.%s Exceeds Maximum",
filename, extension);
return(NULL);
}
// char *filename1 = new(char[len+strlen(extension)+1]);
const int filenameLength = len+strlen(extension)+1;
char *filename1 = new(char[filenameLength]);
strcpy(filename1,filename); // temp filename for appending extension
/* check if file name has .extension */
/* if it does not, add .extension to it */
int i=len-1;
while(i > 0 && filename[i--] != '.');
// printf("\n Comparing %s to %s", extension, filename+i+1);
if(strcmp(extension, filename+i+1) )
strcat(filename1,extension);
if( (strm = fopen(filename1, access) ) == NULL )
{
printf("\n ERROR OPENING FILE %s (mode %s)", filename1,access);
}
delete(filename1);
return(strm);
}
char *filename1 = new(char[filenameLength]);
and
Compiling utilities.cc ...
src/utilities.cc: In function ‘FILE* open_file(char*, const char*, const char*)’:
src/utilities.cc:251: error: ISO C++ forbids variable-size array
gmake: *** [/home/landon/geant4/work/tmp/Linux-g++/exampleN01/utilities.o] Error 1
has occurred. I’ve checked the entire command line but still can’t find the mistake.
The cause: The error: Iso c++ forbids variable length array” happens because VLA (variable size arrays) are not allowed in C++.
You can’t make an array like this on the stack as a local variable length array:
Solution:
Instead, try this:
In addition, when you’ve already given memory for an array, you could perhaps clear memory by using
This error is correct. C++ prohibits variable size arrays (VLA). This is a VLA.
Most likely, you meant this:
This is not a VLA but an array
char
s that are allocated to the heap. This pointer should be deleted using operatordelete[]