I have a question regarding scope for a character array defined as follows:
saveDataObj->save("This is the first entry", 1, 2);
Here is how the SaveData class has been defined:
class SaveData {
struct entry{
const char* data;
int data1;
}
entry* mpData;
static int iter;
}
//Constructor
SaveData::SaveData()
{
//allocates space for 100
mpData = new entry[100];
}
//saves the passed in data
SaveData::save(const char* pData, int intData1)
{
mpData[iter].data = pData;
mpData[iter].data1 = intData1;
iter++;
}
SaveData::print()
{
for (int i=0; i < 100; i++)
cout << "data:" << mpData[i].data << endl;
}
////////////////////////////////////
//I have another class which saves the data by calling save()
TestClass::save1()
{
SaveDataObj->save("This is the first entry", 1, 2);
}
TestClass::save2()
{
SaveDataObj->save("This is the second entry", 1, 2);
}
I'll be saving upto 100 different character arrays.
My question is:
1) Will the character array "This is the first entry" be considered as
local to the function TestClass:save(). Which means this array
will be saved on the stack and will be deleted from the stack
once I exit the function?
2) Is this equivalent to defining a local char pointer as follows:
TestClass::save()
{
const char* pData = "This is the first entry";
SaveDataObj->save(pData, 1, 2);
}
3) In SaveData::save()
SaveData::save(const char* pData, int intData1)
{
mpData[i].data = pData;
mpData[i].data1 = intData1;
}
mpData.data points to passed in pData.
What will happen if I later call print() to dump all the saved data?
Will I able to dump my saved data or will I be dumping garbage?
Please let me know.
(I'm new to this forum and this is my first post.)
Thanks in advance.