Failing to set arrize size with var
Hey guys,
Thanks up front for your help, this seems like a ridiculous problem but I'm stuck on it (drat!).
Anyway, I have a structure and I'm trying to create a string array in the following way.
1 2 3 4 5 6 7 8 9
|
// Populate Structure
cfile.frames = atoi(calHeader[0][1].c_str());
cfile.cameras = atoi(calHeader[1][1].c_str());
cfile.markers = atoi(calHeader[2][1].c_str());
cfile.frequency = atoi(calHeader[3][1].c_str());
// Create String Array with length of # of markers
string mNames[cfile.markers];
|
I get the following errors:
1 2 3
|
error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2466: cannot allocate an array of constant size 0
|
I can print out the value in cfile.markers, it's 52.
I then thought, hm maybe it needs a constant int.
So I tried:
1 2
|
const int SIZE = cfile.markers;
string mNames[SIZE];
|
Still no luck. I'm failing on the instantiation of the array. The following works:
string mNames[52];
works just fine.
Here is the whole function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
struct calFile {
int frames, cameras, markers, frequency;
}; calFile cfile;
void ReadCalFile(void)
{
ifstream calFile("SC0046.tsv", ios::in);
if (calFile.is_open())
{
cout << "File Opened!\n";
stringstream iss;
string line, word;
string calHeader[9][3];
int i=0,j=0;
// Read in cal header file, and fill array.
// Next: Str2num and add to calfile Struct
while (getline(calFile,line))
{
if(i==9) {break;}
iss << line;
while (getline(iss,word,'\t')) {
if(i==7) {
if(j==3) {break;}
calHeader[i][j]=word;
} else {
if(j==2) {break;}
calHeader[i][j]=word;
}
j++;
}
j=0;
iss.clear();
i++;
}
// Populate Structure
cfile.frames = atoi(calHeader[0][1].c_str());
cfile.cameras = atoi(calHeader[1][1].c_str());
cfile.markers = atoi(calHeader[2][1].c_str());
cfile.frequency = atoi(calHeader[3][1].c_str());
// Pull Marker Names
const int SIZE = cfile.markers;
string mNames[SIZE];
//string mNames[cfile.markers];
//getline(calFile,line);
cout << SIZE << endl;
// Close file
calFile.close();
} else {cout << "File did not open\n";}
}
|
I'm using VS2010 and including <string>.
Thanks again.
To specify the size of an array at runtime you have to use dynamic memory allocation. A std::vector is one possible approach:
1 2 3 4 5
|
#include <vector>
//...
// create a vector of strings (with length of # of markers)
std::vector< std::string > mNames( cfile.markers );
|
Okay, thanks a lot moorecm.
Topic archived. No new replies allowed.