Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

c++ - How to create a variable size char array in VC++

const int sizea = 600; 
char sz[sizea];

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];

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

  • most portably, use a dynamic array class such as std::string or std::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).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...