Get odd characters when printing an int dynamic array from a pointer

advertisements

Like the title says, I've been trying to print elements of an array dynamically allocated which is assigned to a pointer. From there I've tried to get it to print out the elements of the array after some elements are added, but I get very strange characters which aren't even ints. Here is some code.

//QS.h
class QS: public QSInterface { //where the pointer is declared
private:
int* quickSort;

//QS.cpp

bool QS::createArray(int capacity) {  //where the array is created
if (quickSort != NULL) {
    //delete [] quickSort;
}
quickSort = new int[capacity];
arrayCap = capacity;
arraySize = 0;
return true;
}

bool QS::addToArray(int value) { //elements are added
if (arraySize >= arrayCap) {
    return false;
}
quickSort = &value;
++arraySize;
return true;

}

string QS::getArray() const {  //where array is "printed"
string array;
for (unsigned int i = 0; i < arraySize; ++i) {
    array += *quickSort + i;
    array += ", ";
}
return array;
}

Output I receive are just nonsensical ASCII characters,not memory addresses. I think I may have messed up when adding to the array. Any help? Thanks

Note *I "have" to use an array, but perhaps in some other world a vector would be nicer


When you execute this line (add function):

quickSort = &value;

you basically set the pointer quickSort to point to the memory address of the parameter value, and stop pointing at the first element of the dynamic array you have created in the beginning. Therefore, you miss all other elements, and you print integer interpretations of random memory data.

Writing instead:

quickSort[size] = value;

will add the value of the parameter value to the memory address allocated for your array, as you would want, without moving the pointer quickSort

Finally, in the last function:

array += *quickSort + i;

can be more neatly replaced by:

array += quickSort[i];

and, just to be sure the conversion from int to string is done correctly

array += to_string(quickSort[i]);