C ++禁止使用可变大小的数组 [英] C++ forbids variable-size array
本文介绍了C ++禁止使用可变大小的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用别人编写的一些现有代码,但无法编译(这里有有限的C经验,但我想学习!).
I am using some existing code that someone else has written, and I cannot get it to compile (limited C experience here but I am trying to learn!).
utilities.cc
#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);
}
这是错误.
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
第251行的错误是
char *filename1 = new(char[filenameLength]);
如果您需要任何其他信息,请告诉我.
If you need any additional information let me know please.
推荐答案
该错误是正确的.C ++中禁止使用VLA(可变大小数组).这是一个VLA:
The error is correct. VLA(variable size arrays) are forbidden in C++. This is a VLA:
char filename1char[filenameLength];
您可能是这个意思:
char *filename1 = new char[filenameLength];
这不是VLA,而是在堆上分配的 char
数组.请注意,您应该使用运算符 delete []
:
Which is not a VLA, but an array of char
s allocated on the heap. Note that you should delete this pointer using operator delete[]
:
delete[] filename1;
这篇关于C ++禁止使用可变大小的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文