-
Array of Structures
hey all, Just wondering if someone might know what is going wrong here.
I have a file that looks like this ...
Code:
...
V 2 103 362731.9 5606201.4 896.2
V 2 104 362722.8 5606184.1 895.8
V 2875 101 361697.7 5607396.2 902
V 2875 102 361687 5607386 902.2
...
... but with tons of lines in it. And im tring to load it up into an
array of structures. However when i try to display the data back to make
sure its all there. I only get the last line of data, then a bunch of garbage.
Heres the code im using ...
Code:
struct coordinate_data
{
char byte;
int lineNumber, binNumber;
double xcoord, ycoord;
float elevation;
};
typedef struct coordinate_data Data;
void GenerateCoordFile(char fileName[])
{
Data *Records;
short Size = 0;
Records = NULL;
fstream inFile(fileName, ios::in);
if(!inFile)
{
cerr << endl << "Input file " << fileName << " could not be opened!" << endl;
abnormalCompletion();
exit(1);
}
do
{
if(!NewElement(Records, Size))
{
cerr << endl << "Insufficent memory to store additional records." << endl;
abnormalCompletion();
exit(1);
}
}while(inFile >> Records->byte >> Records->lineNumber >> Records->binNumber
>> Records->xcoord >> Records->ycoord >> Records->elevation);
DisplayData(Records, Size);
delete [] Records;
}
short NewElement(Data *& Records, short & Size)
{
Data *temp;
temp = new Data[Size+1];
if(temp == NULL)
{
return 1;
}
memcpy(temp, Records, (sizeof(Data) * Size++));
delete [] Records;
Records = temp;
return 1;
}
void DisplayData(Data *& Records, short Size)
{
Data *END = Records + Size,
*search;
search = Records;
while(search < END)
{
cout << fixed << setprecision(1)
<< search->byte << "\t" << search->lineNumber << "\t" << search->binNumber << "\t"
<< search->xcoord << "\t" << search->ycoord << "\t" << search->elevation << "\r";
search++;
}
}
Any help would be great ... thanks.
-
>> inFile >> Records->byte
Records is an array, but you're using it like a plain pointer. Did you want Records[size-1].byte instead?
-
well when i add a cout to the do while loop, it seems to be reading it in correctly. Its just when i display it back. It only has the last line, then garbage.
-
That's because when you use an array like a pointer, you are modifying the first element in the array. So because of the problem I mentioned, your code modifies the first element in the array over and over, which overwrites the previous line of data each time. When it is done, only the last line of data is stored, and it is stored in the first slot in the array. The rest of the array is left untouched and is therefore filled with garbage.
-
You are always reading into Records->xxx - Records always points to the FIRST element.
You want to read into.
Records[size-1].xxx, as that is the LAST element in the list.
Edit: Daved beat me to it. Got to learn to type quicker (not to mention that Daved already said this was the problem EARLIER).
--
Mats
-
Thank you very much guys. All is good now, i really appreciate it.