Implement the vector insert function in c++ - c++

I'm trying to implement vector's insert function in c++. The basic idea is
initialize a tmp_vector with the size of the new array;
2.copy the original data into a tmp_vector;
delete the old vector; copy the
tmp_vector to new_vector
Here's my code:
double* Vector::insert(int index, double *newNum, int newNum_size)
{
//insert into empty vector
if(size == 0){
//if there's enough memory to hold newNum
if(newNum_size < capacity)
{
for(int i = 0; i < newNum_size; i++)
{
data[i] = newNum[i];
}
}
}
//expand the vector
if(size != 0){
double *tmp_vector = NULL;
try{
tmp_vector = new double(size+newNum_size);
}
catch(bad_alloc &e){
cerr << "Vector::insertion(): " << e.what();
}
//move the vector to tmp
for(int i=0; i < size; i++)
{
tmp_vector[i] = data[i];
}
//copy the tmp_vector pointer to newNum pointer
tmp_vector[size+newNum_size] = *newNum;
//realease the memory from data
delete[] data;
}
return newNum;
}
However, it gives me a compile error when I call it from main
myVector.insert(0,1.0,1);
The error is "Cannot initialize a parameter type 'double' with an rvalue of type 'double'". What does this mean?

You have:
(int index, double *newNum, int newNum_size)
(0, 1.0, 1)
I think the problem is that 1.0 is not a double[*]... it's just a double.

How about using the STL implementation? This way you can avoid unnecessary complications. http://www.cplusplus.com/reference/vector/vector/insert/

In the signature of your function:
double* Vector::insert(int index, double *newNum, int newNum_size)
you are expecting double pointer/an array of doubles, whereas in insert(0,1.0,1) you are passing a single double value.
Moreover, I don't see where did size variable come from. Provided you would have it declared inside the function/passed to a function, this would be incorrect: tmp_vector = new double(size+newNum_size) and what you want is probably: tmp_vector = new double(size*newNum_size) (the latter would allocate newNum_size times size memory, i.e. space for your array).

Related

Creating a custom vector class. Push_back function only working for the first value

In my Comp Sci class, we are learning how to make our own vector class. We will eventually store our custom made string class objects in a custom made vector class. I wanted to try and build a vector class of integers beforehand for simplicity.
So far, I have a default constructor that initializes my pointer to an empty array and sets the size to 0. Then I try to append some values using my push_back function and then check to make sure it was done correctly.
When I do std::cout << v[0] << std::endl;
I get the correct output (10). However, if I call push_back again and then call v[1] I get 0.
I feel like I am not allocating memory correctly in my push_back function but I am not sure.
Thanks for any advice!
[part 1][1]
[part 2][2]
sorry if my formatting is wrong I am new to posting here.
class:
class myVector
{
private:
int *data; //will point to an array of ints
size_t size; //determins the size of array
public:
myVector(); // default constructor
void push_back(int); // appends an integer to the vector
int operator[](size_t);
size_t sizeOf();
};
main:
int main()
{
myVector v;
v.push_back(10);
std::cout << v.sizeOf() << std::endl;
v.push_back(14);
std::cout << v.sizeOf() << std::endl;
std::cout << v[1] << std::endl;
return 0;
}
member functions:
size_t myVector::sizeOf()
{
return size;
}
int myVector::operator[](size_t location)
{
return this->data[location]; //this will return the value at data +
//location
}
myVector::myVector()
{
this->data = new int[0]; //initialize the data to an empty array of
//ints
size = 0; //initialize the size to 0
}
void myVector::push_back(int val)
{
if(size == 0) //if size == 0, create a new array with 1 extra index
{
++size;
delete [] this->data;
this->data = new int[size];
this->data[0] = val;
}
else
{
++size;
int *temp = new int[size - 1];
for(int i = 0; i != (size - 1); i++)
{
temp[i] = this->data[i];
}
delete [] this->data;
this->data = new int[size];
for(int i = 0; i != (size - 1); i++)
{
this->data[i] = temp[i];
}
this->data[size] = val;
delete [] temp;
}
}
In your code:
this->data[size] = val;
you are going outside of the allocated array.
Same in the previous loop (in its last iteration):
for(int i = 0; i != (size - 1); i++)
{
this->data[i] = temp[i];
}
There are a few problems.
It does not look like you need a special case for 0 sized vector
you do not allocate enough memory:
Example, if size is one, you hit this case, then size becomes 2, and you allocate a buffer of ... 1.
else
{
++size;
int *temp = new int[size - 1];
for(int i = 0; i != (size - 1); i++)
{
temp[i] = this->data[i];
}
Tip: use ```for (int i = 0; i < size; ++i)``` and ```new int[size]```
you go out of bounds after your loop. If you allocate [size] bytes, then (size-1) is the last valid index.
you copy data into temp, then copy temp into ANOTHER allocation. You don't need to do that. Just assign this->data = temp; The whole second loop is needless, and don't delete temp at the end.
Its not necessary to a lot of new and delete operations and loops. I fixed and cleaned your two functions.
myVector::myVector()
{
this->data = new int[1]; //initialize the data to an empty array of
//ints
size = 0; //initialize the size to 0
}
void myVector::push_back(int val)
{
if(size == 0) //if size == 0, create a new array with 1 extra index
{
++size;
this->data[0] = val;
}
else
{
++size;
int *temp = new int[size];
for(int i = 0; i != (size-1); ++i)
{
temp[i] = this->data[i];
}
delete [] this->data;
this->data = temp;
this->data[size-1]=val;
}
}
in push_back function allocate a new array with new size and copy data from existing array. After deleting existing array and we see this->data can't point to valid location. Assign the new array's address to this->data and we access existing data and size increased +1. Last we assign parameter val to end of array(size-1).

Errors with dynamic Array created with new after passed to resize function

I am trying to implement a dynamically created array using new that I want to resize but the resize action is not working correctly.
This is an exercise on dynamic arrays, so I need dynamic arrays using new and not std::vector.
Here is my code :
int main ()
{
// Build an application here
int length = 0;
int size = 0;
int input;
bool endAdding = false;
cout << "Please enter the length of the new array : ";
cin >> length;
int* oPtrDynamicArray = CreateDynamicArray (length, size);
do
{
cout << "Add an element (0 to quit) : " << endl;
cin >> input;
cout << endl << endl;
if (input == 0){
endAdding = true;
}
else
{
InsertElement(oPtrDynamicArray, input, size, length);
}
cout << "The array contains : " << endl;
for (int i = 0; i < size; i++)
{
cout << i << ": [" << oPtrDynamicArray[i] << "]" << endl;
}
} while (!endAdding);
DeleteDynamicArray (oPtrDynamicArray, size);
}
int *CreateDynamicArray (int capacity, int &size)
{
size = 0;
return new int[capacity];
}
void DeleteDynamicArray (int *dynamicArray, int &size)
{
delete[] dynamicArray;
dynamicArray = nullptr;
size = 0;
}
void InsertElement (int *dynamicArray, int element, int &size, int capacity)
{
if (capacity <= size)
{
ResizeDynamicArray (&dynamicArray, size+1);
}
dynamicArray[size] = element;
size++;
}
void ResizeDynamicArray (int **dynamicArray, int newCapacity)
{
int ** newArray = new int*[newCapacity];
for (int i = 0; i < newCapacity; i++)
{
newArray[i] = dynamicArray[i];
}
*dynamicArray = *newArray;
delete[] newArray;
newArray = nullptr;
}
The problem is that the array is passed to my InsertElement() function and then to ResizeDynamicArray() only if capacity <= size, but the array passed to the first function, is passed with good values, but with abnormal pointers in the array.
Example :
For an array of 3, I have :
array[0] = 1 --> adress 0x0004e300 containing value 1
array[1] = 2 --> adress 0x00000003 containing ???
array[2] = 3 --> adress 0x008ffb24 containing value 2
I really don't understand, it would be really great if someone could explain my error :/.
The problem is here
void InsertElement (int *dynamicArray, int element, int &size, int capacity)
{
if (capacity <= size)
{
ResizeDynamicArray (&dynamicArray, size+1);
}
dynamicArray[size] = element;
size++;
}
when you call ResizeDynamicArray you are changing the dynamicArray pointer declared as a parameter to InsertElement. You are not changing the oPtrDynamicArray pointer in main.
If you want to make this work you need to change InsertElement to take a double pointer (just like ResizeDynamicArray)
void InsertElement (int **dynamicArray, int element, int &size, int capacity)
{
if (capacity <= size)
{
ResizeDynamicArray (dynamicArray, size+1);
}
(*dynamicArray)[size] = element;
size++;
}
Or you could do the easy thing and just use std::vector<int>.
EDIT now that I look at it your ResizeDynamicArray function I see that function is completely wrong as well. It's clear that you have some learning to do with pointers
Here's how ResizeDynamicArray should be
void ResizeDynamicArray (int **dynamicArray, int newCapacity)
{
int * newArray = new int[newCapacity];
for (int i = 0; i < newCapacity; i++)
{
newArray[i] = (*dynamicArray)[i];
}
delete[] *dynamicArray;
*dynamicArray = newArray;
}
You're not the first newbie to fail to understand pointers. Have a good look at the code above and compare it with your code. The main difference is that my code using a pointer to change what is being pointed to. Your code tried to change the pointer itself, which is incorrect. It's confusing because what is being pointed to is another pointer (the dynamic array).
There are several issues in your code:
First, in ResizeDynamicArray, you allocate an array of pointers to ints, not an array of ints. int ** newArray = new int*[newCapacity] should be int *newArray = new int[newCapacity].
Second, once you have fixed that, you need to write *dynamicArray = newArray;;
but you should free the old array before you assign the pointer to the new memory block.
void ResizeDynamicArray (int **dynamicArray, int newCapacity)
{
int *newArray = new int[newCapacity];
for (int i = 0; i < newCapacity; i++)
{
newArray[i] = (*dynamicArray)[i];
}
delete[] *dynamicArray;
*dynamicArray = newArray;
}
Third, you since InsertElement may call ResizeDynamicArray (which will give you back a new memory block), you need to alter the originally passed pointer. So you need to pass a pointer to a pointer int the function, just as you did with ResizeDynamicArray:
void InsertElement (int **dynamicArray, int element, int &size, int capacity)
adapt the body accordingly then.
I know the question is already answered but not the why.
You have to keep in mind that pointers are passed to functions by value.
The pointer value, the address it points to, is lost when the function ends.
But you are still able to change the value stored at the address it points to by dereferencing the pointer.
To pass be able to change the pointer value, the address it points to, inside a function, you have to pass a pointer to a pointer. In this case passing a double pointer is synonym for passing a pointer to a function by reference.
void Foo(int **ptr)
{
// Don't use ptr, changes are lost after function end as ptr is a local copy
// Use *ptr to change the value of the pointer you passed to the function.
// Use **ptr to change the value at the address the pointer you passed to the funcion points to
}
In this case you can change the pointer value, the address it points to, by dereferencing the double pointer once. Which applies to above answers.

How to write a procedure to modify the elements and size of a dynamic array without knowing the size?

The following is a question from an exam in programming I had recently. Neither me nor the other students have found a way of solving it. The professor says it is possible, however refused to tell us what the solution is. The question:
Write a procedure with a header of:
void ArrayUpdate( int ??? array, int ??? delAmount, int ??? addAmout)
The procedure is used to modify elements of a dynamic array passed through the first argument.
The procedure should remove the delAmount of the first cells from the array. It should also add addAmount of elements to the back of the array with whole numbers read from std::cin.
The "???" need to be replaced or removed.
Square brackets "[ ]" can only be used with new or delete.
Only iostream and fstream may be included. (fstream was needed for another question, so it may not be needed here.)
"The procedure is used to modify elements of a dynamic array passed through the first argument." It does not say how the array is organized. The first element, as #user4581301 suggested, might be the size of the array. In other words, the first element of the array is at position 1, not 0. This is most likely what your teacher had in mind. The purpose is to teach you pointers/references and the array layout.
Creating an array:
void CreateArray( int*& array, int size )
{
array = new int[ size + 1 ];
array[ 0 ] = size;
}
You may use int** instead of int*&, but it is harder to write/read.
Retrieving the size:
int ArraySize( int* array )
{
return *array;
}
Usage:
int* array;
CreateArray( array, 10 );
//...
for ( int i = 1; i <= ArraySize(array); ++i )
// ...
Function signature:
void ArrayUpdate( int*& array, int delAmount, int addAmout);
Here's my hack-cut at the problem. It's very similar to ZDF's, but it adds the array's capacity to the book-keeping and lies and hides the book-keeping by giving the caller a pointer to the middle of the array rather than the beginning. This allows the user to use the array as a regular array, but will crash if they try to delete it themselves.
Comments embedded where I figured more explanation was required.
//Magic numbers are evil.
constexpr int bookkeeping = 2;
constexpr int sizeOff = -2;
constexpr int capOff = -1;
void ArrayUpdate( int *& array, int delAmount, int addAmount)
{
int size;
int capacity;
// can't do jack with a non-existent array, so let's make sure we have one.
if (array != nullptr)
{
size = *(array + sizeOff);
capacity = *(array + capOff);
}
else
{
size = 0;
capacity = 0;
}
if (delAmount > size) // can't delete more than we have.
{
delAmount = size;
// alternative: freak out here. Abort, throw exception, whatever
}
int * to; // track where data goes to
int * temp; // location of new buffer, if resized
bool resized;
int newsize =size + addAmount - delAmount;
if (newsize > capacity)
{
capacity *=2;
if (capacity < newsize)
{
capacity = newsize;
}
temp = new int[capacity+bookkeeping];
to = temp + bookkeeping; // point to where we want data to go:
// after the book-keeping.
resized = true;
}
else
{
to = array;
resized = false;
}
// use std::copy or memcpy here, but since we're not allowed the appropriate
// headers, here comes ol' brute force!
if (delAmount || resized) // need to copy old data around
{
for (int index = delAmount; index < size; index++)
{
*to++ = *(array + index);
}
}
// add new data
for (int count = 0; count < addAmount; count++)
{
if (std::cin >> *to) // always test to make sure you got good input
{
to++;
}
else
{ // Bad input. Clean up
std::cin.clear();
// normally I'd use cin.ignore(numeric_limits<streamsize>::max(), '\n')
// here to kill all the remaining user input, but no <limits>
std::cin.ignore(1000, '\n');
// might also want to just read and discard until you find the
// first whitespace. That's can be done easily by >> to a std::string,
// but no string header allowed.
}
}
if (resized)
{
if (array != nullptr) // normally deleting nullptr is safe, but not when
// you're going to modify it with an offset
{
delete[] (array - bookkeeping);
}
array = temp + bookkeeping; // array hides the extra book-keeping
*(array + capOff) = capacity;
}
if (array != nullptr)
{
*(array + sizeOff) = newsize;
}
}
Not exhaustively tested. May be a bug or two in there.
For completeness, here's test code and a Free Array routine:
void FreeArray(int * array)
{
delete[] (array - bookkeeping);
}
void printarray(const int * array)
{
int size;
int capacity;
if (array != nullptr)
{
size = *(array + sizeOff);
capacity = *(array + capOff);
}
else
{
size = 0;
capacity = 0;
}
std::cout << "Size: " << size <<"\nCapacity: "<< capacity << '\n';
for (int index = 0; index < size; index++)
{
std::cout << array[index] << ' ';
}
std::cout << std::endl;
}
int main()
{
int * array = nullptr;
printarray(array);
ArrayUpdate(array, 5, 0);
printarray(array);
ArrayUpdate(array, 5, 5);
printarray(array);
ArrayUpdate(array, 5, 5);
printarray(array);
ArrayUpdate(array, 0, 5);
printarray(array);
ArrayUpdate(array, 5, 0);
printarray(array);
}
If "???" can be replaced by whatever you want, so you can pass to your function a pointer to an int, or a pointer to pointer to int, etc...
So the trick in C++ when dealing with memory management, or range, is to store 2 pointers one to the begin of the array and one to its end:
//a range:
int* limits[2];
int ** array = limits;
Then if you change the size of the range inside a function you must pass it by reference:
void ArrayUpdate( int ** array, int delAmount, int addAmout){
int* begin = array[0];
int* end = array[1];
//end so on
}

Problems with copying an array into another dynamic array

I have a problem with the execution of this program. I do not know why it ends up running so abruptly ("The program stopped working"). The results of it are what I hope, however that happens. And I tried many things to avoid it and found that what causes the error is the function void IntArr::addElement(int qtty,int *vec); since if I remove it, the program finishes perfectly and without any error. Analyze the function and for me it's fine, I do not know what is slipping from my hands. The function that what you should do is pass an array with the amount of elements that I want from it and add them to another array.
PS: the original program was well divided by files (class.h, class.cpp, main.cpp), nothing more than to copy them here I had to paste everything together.
I would appreciate your help. Regards!
#include <iostream>
using std::cout;
using std::endl;
#define PRESS_KEY std::cout<<"\nPresione Enter para continuar . . .\n";std::cin.get();
class IntArr{
private:
int * p;
int size;
int used;
//Verificador
void redimensionador(int cant);
public:
//Constructores
IntArr (int sz);
IntArr (int sz,int qtty,int *vec);
//Destructor
~IntArr();
//Visualizadores
void prtArr (void) const;
void prtArr (int cant);
//Accesores
int getSize(){return size;};
int getUsed(){return used;};
//Operaciones
void addElement(int xx);
void addElement(int qtty,int *vec);
};
//Constructores
IntArr::IntArr(int sz){
size = sz;
used = 0;
p = new int[size];
}
IntArr::IntArr(int sz,int qtty,int* vec){
if(qtty>sz){
sz = qtty;
}
size = sz;
used = qtty;
p = new int[size];
p = vec;
}
//Destructor
IntArr::~IntArr(){
delete []p;
}
//Visualizadores
void IntArr::prtArr(void) const{
if(used == 0){
cout<<endl<<"El array no tiene elementos."<<endl;
}
else{
cout<<endl<<"Array: ";
for(int i=0;i<used;i++){
cout<<p[i]<<", ";
}
cout<<endl;
}
}
void IntArr::prtArr(int cant){
if(used == 0){
cout<<endl<<"El array no tiene elementos."<<endl;
}
else{
cout<<endl<<"Array: ";
for(int i=0;i<cant;i++){
cout<<p[i]<<", ";
}
cout<<endl;
}
}
//Operaciones
double IntArr::getAvg(){
double acum = 0;
for(int i=0;i<used;i++){
acum += p[i];
}
return (acum/used);
}
void IntArr::addElement(int xx){
redimensionador(1);
p[used] = xx;
used++;
}
void IntArr::addElement(int qtty,int *vec){
int j=0;
redimensionador(qtty);
for(int i=used;i<(used+qtty);i++){
p[i] = vec[j];
j++;
}
used += qtty;
}
//Verificador
void IntArr::redimensionador(int cant){
if(cant+used>size){
if(cant > 5){
size += cant;
}
else{
size += 5 + cant;
}
}
}
int main(int argc, char *argv[]){
int v_aux[]= {0,5,10,15,20,25,30,35,40};
IntArr A(10,sizeof(v_aux)/sizeof(int),v_aux);
cout<<" size:"<<A.getSize()<<endl<<" used:"<<A.getUsed()<<endl;
A.prtArr();
A.addElement(77);
cout<<" size:"<<A.getSize()<<endl<<" used:"<<A.getUsed()<<endl;
A.prtArr();
A.addElement(11);
cout<<" size:"<<A.getSize()<<endl<<" used:"<<A.getUsed()<<endl;
A.prtArr();
A.addElement(8,v_aux);
cout<<" size:"<<A.getSize()<<endl<<" used:"<<A.getUsed()<<endl;
A.prtArr();
PRESS_KEY;
}
One problem I noticed is in the following lines:
p = new int[size];
p = vec;
When you do that:
You have a memory leak. The value returned by new int[size] is lost to your program.
You point p to the statically defined array in main. That leads to undefined behavior when you use delete [] p; in the destructor.
I am guessing you want to copy the values from vec to p. You'll have to copy the values one by one.
The manually coded version for that:
for (int i = 0; i < used; ++i )
{
p[i] = vec[i];
}
Using the standard library function std::copy:
std::copy(vec, vec+used, p);
If you run out of memory, you can not just say you have more size by adding to an integer. You have to reallocate the memory, copy the values from the old array into the new array, then delete the old array.
You also need to be careful here. Raw pointers are error prone, and I see you have some strange constructs here. For example, IntArr::IntArr(int sz,int qtty,int* vec) you allocate a pointer, then immediately overwrite it. That allocation is a leak.
Be sure you properly update size and used so that you don't lose track of how much memory you actually have. When size changes, so must your buffer or you are out of sync.
Even this constructor has a memory leak and can result in undefined behaviour (for example when vec points to first element of a local array or when the array poined by the argument vec will be deleted).
IntArr::IntArr(int sz,int qtty,int* vec){
if(qtty>sz){
sz = qtty;
}
size = sz;
used = qtty;
p = new int[size];
p = vec;
}
At first a memory is allocated and its address is assigned to p and then p is reassigned.
p = new int[size];
p = vec;
You have to copy elements from the array pointed to by the argument vec into the allocated memory pointed to by the data member p.
And this member function
void IntArr::redimensionador(int cant){
if(cant+used>size){
if(cant > 5){
size += cant;
}
else{
size += 5 + cant;
}
}
}
does not make sense. You have to reallocate the original array pointed to by the data member p.

Unitialized local variable and help correcting

I am learning about pointers and the new operator in class.
In my readArray function I am to read in a size. Use the size to dynamically create an integer array. Then assign the array to a pointer, fill it, and return the size and array.
I believe I've gotten that part corrected and fixed but when I try to sort the array, i get the error "uninitialized local variable temp used."
The problem is though I get that error when I am trying to intialize it.
Any help appreciated thank you. Seeing my errors is very helpful for me.
#include <iostream>
using namespace std;
int* readArray(int&);
void sortArray(int *, const int * );
int main ()
{
int size = 0;
int *arrPTR = readArray(size);
const int *sizePTR = &size;
sortArray(arrPTR, sizePTR);
cout<<arrPTR[1]<<arrPTR[2]<<arrPTR[3]<<arrPTR[4];
system("pause");
return 0;
}
int* readArray(int &size)
{
cout<<"Enter a number for size of array.\n";
cin>>size;
int *arrPTR = new int[size];
for(int count = 0; count < (size-1); count++)
{
cout<<"Enter positive numbers to completely fill the array.\n";
cin>>*(arrPTR+count);
}
return arrPTR;
}
void sortArray(int *arrPTR, const int *sizePTR)
{
int *temp;
bool *swap;
do
{
swap = false;
for(int count = 0; count < (*sizePTR - 1); count++)
{
if(arrPTR[count] > arrPTR[count+1])
{
*temp = arrPTR[count];
arrPTR[count] = arrPTR[count+1];
arrPTR[count+1] = *temp;
*swap = true;
}
}
}while (swap);
}
You make temp an int pointer (uninitiialized), and then set the thing it points at (anything/nothing) to arrPTR[ccount]. Since you are using temp only to swap, it should be the same type as those being swapped, in this case: an int.
If it absolutely must be a pointer (there is no good reason for this, it's slow, confusing, adds potential for errors, and adds potential for memory leaks):
int *temp = new int; //make an int for the pointer to point at
bool *swap = new bool; //make an bool for the pointer to point at
do
{
//your code
}while (swap);
delete temp;
delete swap;
You declared temp as a pointer. You need to allocate it on the heap before dereferencing and assigning to it later. However perhaps a variable on the stack would be preferable?
FYI: You should be aware of the memory leak in readArray as well which is leaving callers responsible for calling delete []
Edit: I hope this will help clear up some of the other problems.
#include <iostream>
int* readArray(int&);
void sortArray(int*, int);
int main ()
{
int size(0); // use stack when possible
int *arrPTR = readArray(size);
sortArray(arrPTR, size);
// arrays are zero based index so loop from 0 to size
for (int index(0); index < size; ++index)
std::cout << arrPTR[index];
delete [] arrPTR; // remember to delete array or we have a memory leak!
// note: because we did new[] for an array we match it with delete[]
// if we just did new we would match it with delete
system("pause");
return 0;
}
int* readArray(int& size)
{
std::cout << "Enter a number for size of array.\n";
std::cin >> size;
int *arrPTR = new int[size]; // all news must be deleted!
// prefer pre-increment to post-increment where you can
for(int count(0); count < size; ++count)
{
std::cout << "Enter positive numbers to completely fill the array.\n";
std::cin >> arrPTR[count];
}
return arrPTR;
}
// passing size by value is fine (it may be smaller than pointer on some architectures)
void sortArray(int *arrPTR, int size)
{
// you may want to check if size >= 2 for sanity
// we do the two loops to avoid going out of bounds of array on last iteration
for(int i(0); i < size-1; ++i) // the first to compare (all except last)
{
for(int j(i+1); j < size; ++j) // the second to compare (all except first)
{
// do comparison
if (arrPTR[i] > arrPTR[j]) // from smallest to biggest (use < to go from biggest to smallest)
{
// swap if needed
int temp(arrPTR[i]); // put this on stack
arrPTR[i] = arrPTR[j];
arrPTR[j] = temp;
}
}
}
}
temp is a "pointer to int, which you're not initializing. When you say *temp = ... you're actually assigning to whatever temp happens to be pointing, but since you haven't told it what to point to, it can write pretty much anywhere in the address space of your program.
Because of the way you're using them, it seems that temp and swap shouldn't be pointers at all, just a plain int and bool.
You didn't initialize the temp pointer do when you dereference it you are writing to a random part of memory. Temp doesn't need to be a pointer, it can just be an int. Just replace EVERY instance of *temp with temp.