Reputation: 1426
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
Upvotes: 6
Views: 24272
Reputation: 66
I did something like this long time ago the Idea is to work with pointers.
so you need to make structure that has (char and nextPointer) the char represent the current value of the array and the nextPointer represent the next structure of the series
looping all through that pointers u will have your array of whatever you want your structure connected
struct yourStructure {
Char char;
double nextPointer;
} ;
so you create first structure and connect to the second and the tree
Upvotes: 0
Reputation: 21
you can use vector as a dynamic array. Try this.
#include <vector> // use this header
#include <iostream>
using namespace std; // use this namespace
int main()
{
vector<int> v; //declare dynamic array equivalent
for (int i = 0; i < 10; ++i) {
v.push_back(10 + i);
}
cout << "vector data: " << endl;
print_collection(v);
while (v.begin() != v.end()) {
cout << "v.back(): "; print_elem(v.back()); cout << endl;
v.pop_back();
}
}
Upvotes: 2
Reputation: 254631
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
or std::vector<char>
;Upvotes: 5
Reputation: 1447
It produces an error because GetLength()
returns you an arbitrary value, not statically defined.
The proper way is to allocate enough memory to hold your string and, if required, the NULL
-terminated symbol either by calling malloc
or by using the new
operator (if compiling with C++ compiler).
Upvotes: 0
Reputation: 5469
Normal use-case is to use new
(and delete
when you're done) for variable-sized elements. If you must use the stack, you can use alloca
.
char *psz = new char[size+1]; // +1 you probably want zero-termination
...
delete [] psz;
Upvotes: 2