Writing to a struct in an array
I have a structure in which there is another structure which has an array of 512 pointers to it.. if that made no sense:
Code:
struct TREEFILE
{
char *name;
struct FILEINFO
{
char *field;
char *key;
char *value;
}*fileInfo[512];
};
What I want to do is assign values to that substructure with the array being at any one of those 512, once again if that made no sense.. lets say Ive already set int arrayLine to be 0:
Code:
strcpy(tFile.fileInfo[arrayLine]->key, "_FIELD_");
strcpy(tFile.fileInfo[arrayLine]->key, "_KEY_");
strcpy(tFile.fileInfo[arrayLine]->key, "_VALUE_");
This compiles all well and fine, but as soon as the program runs I get an illegal opperation... and those lines, well any one by itself is causing the problem. Ive also figured out that I only get problems when I try to add a value to that sub-structure. So this works:
Code:
tFile.fileInfo[arrayLine]->key;
/* But this wont */
strcpy(tFile.fileInfo[arrayLine]->key, "_VALUE_");
Im lead to believe my problem could be allocating the right amount of memory, or some problem with writing to memory.
Sorry that this may be tough to understand, but its 4am :)
If anyone has any ideas or answers thatd be great. Thanks.
Re: Writing to a struct in an array
In the following:
Code:
strcpy(tFile.fileInfo[arrayLine]->key, "_FIELD_");
strcpy(tFile.fileInfo[arrayLine]->key, "_KEY_");
strcpy(tFile.fileInfo[arrayLine]->key, "_VALUE_");
The data you are copying from are constants. The destination is specifed using ponters, as others have indicated. You need to have storage for the strings pointed to. Yet in the case of constants the memory will already exist. So you might be able to do:
Code:
tFile.fileInfo[arrayLine]->key = "_FIELD_";
tFile.fileInfo[arrayLine]->key = "_KEY_";
tFile.fileInfo[arrayLine]->key = "_VALUE_";
That sets the pointers to the address of the string constants. This would not work if you need to change the strings.
Alternatively something such as the following would work:
Code:
tFile.fileInfo[arrayLine]->key = new char[8];
strcpy(tFile.fileInfo[arrayLine]->key, "_FIELD_");
tFile.fileInfo[arrayLine]->key = new char[6];
strcpy(tFile.fileInfo[arrayLine]->key, "_KEY_");
tFile.fileInfo[arrayLine]->key = new char[8];
strcpy(tFile.fileInfo[arrayLine]->key, "_VALUE_");
// Use the strings, then when you are through:
delete [] tFile.fileInfo[arrayLine]->key;
delete [] tFile.fileInfo[arrayLine]->key;
delete [] tFile.fileInfo[arrayLine]->key;
Doing fancy things like constructors and destructors is probably worthwhile but probably are also not necessary.