如何在VC ++中创建可变大小的char数组 [英] How to create a variable size char array in VC++
问题描述
const int sizea = 600;
char sz[sizea];
上面的代码可以正常工作。但是下面的代码段导致错误。
我正在使用visual studio 2005 - MFC应用程序
above code works fine. But below code segment cause errors. I'm working on visual studio 2005 - MFC application
CString strFinal;
.......//strFinal value is dynamically changing . .
const int size = strFinal.GetLength();
char sz[size];
错误2错误C2057:预期常数表达式
错误5错误C2070:'char []':非法sizeof操作数
错误4错误C2133:'sz':未知大小错误3错误C2466:不能分配
的数组常量大小0
Error 2 error C2057: expected constant expression
Error 5 error C2070: 'char []': illegal sizeof operand
Error 4 error C2133: 'sz' : unknown size Error 3 error C2466: cannot allocate an array of constant size 0
推荐答案
在当前版本的C ++中,数组必须有固定大小,编译时常量。如果您需要使用运行时值,那么您的选项是:
In the current version of C++, arrays must have a fixed size, specified by a compile-time constant. If you need to use a run-time value, then your options are:
- 最便携地使用动态数组类,例如
std :: string
或std :: vector< char>
; - 支持C99可变长度数组作为非标准扩展的编译器;
- 等待一年动态数组(希望)在C ++ 14中引入(也许等待更长时间为您的编译器供应商赶上)。
- most portably, use a dynamic array class such as
std::string
orstd::vector<char>
; - use a compiler that supports C99 variable-length arrays as a non-standard extension;
- wait a year for dynamic arrays to (hopefully) be introduced in C++14 (and perhaps wait a bit longer for your compiler vendor to catch up).
这篇关于如何在VC ++中创建可变大小的char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!