I'm new in C++ and trying to learn C++ by myself. I wrote codes for my project but I'm experiencing difficulties returning an array from an accessor of a class.
I have a class called LoadData which accept array_a[]. LoadData class constructor copies memory block of array_a to arrayA. An accessor, getArray() attempt to return a pointer to arrayA.
In main(), I create an array of objects, objVec[obj_i], which collects data and store in the class. When I try to return an array from LoadData and print out the contents, I get only the first element of the array correctly and the rest seems to be returning the memory addresses.
I believe that the problem I'm having is either in the way I'm returning an array in accessor or the way I'm calling getArray(). I also have lot of trouble using pointers.
I'm struggling with this for about a week so any suggestions and inputs would be appreciated! Thank you very much in advance.
class LoadData{
private:
float* arrayA;
public:
//constructor
LoadData(float array_a[])
//accessor
float getArray(){return* arrayA}
};
LoadData::LoadData(float array_a[]){
arrayA = new float[sizeOfArray]
memcpy(arrayA, array_a, sizeof(int)*sizeOfArray);
}
int main(){
class LoadData;
int objSize = 6;
LoadData **objVec = new LoadData*[objSize];
obj_i = 0;
//loop to load data
while (...){
objVec[obj_i] = new LoadData(array_a)
}
float *copyArray;
*copyArray = objVec[1]->getArray();
for (int i = 0; i<sizeOfArray; i++){
cout<<*(copyArray + i) <<'\t';
}
//end of main
}
I'm new in C++ and trying to learn C++ by myselfThen may I suggest you drop this and usestd::vectorinstead. What seems simple to you in your current example will become a headache as soon as you start to write anything other than a toy program.