adding char[] to dynamic array and deallocate from a function - c++

I need some help since I'm new to c++, I have a homework question where we should read a name to a char[] and then place that input inside a dynamic array, sort the dynamic array, and then terminate the allocated memory. We have to work with a half-done written program and I don't think I'm getting the input incorrectly in the dynamic array and I have a problem with deallocating memory could someone help with some tips maybe? My contribution to the code is highlighted in ** ** thanks!
const int BUFLEN = 100; // Max length of reading buffer
void sort(char* friendList[], int n); // n is the number of elements
void print(char* friendList[], int n); // n is the number of elements
void terminate(char* friendList[], int n); // n is the number of elements
const int AMOUNT = 5;
int main()
{
char* friends[AMOUNT]; // Dynamic array with AMOUNT pcs of string pointers
char buff[BUFLEN] = { "" }; // Creates a string buffer (null terminated)
int count = 0;
while (count < AMOUNT) // enter AMOUNT number of friends
{
cout << "Name a friend: ";
cin.getline(buff, BUFLEN); // Temporary reading into string buffer
friends[count] = **new char[AMOUNT];** //. . . WRITE CODE allocating memory to the string
// WRITE CODE that adds loaded name to current location in the dynamic array
**strcpy(friends[count], buff);**
++count;
}
sort(friends, count); // Sorts the ‘count’ strings
print(friends, count); // Prints the ‘count’ first names
terminate(friends, count);// Releases all allocated memory space
return 0;
}
void sort(char* friendList[], int n)
{
// WRITE FUNCTION that sorts the strings in the friendList in alphabetical order!
**int result;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
result = strcmp(friendList[j+1], friendList[j]);
if (result < 0)
swap(friendList[j+1], friendList[j]);
}
}**
}
void print(char* friendList[], int n)
{
// WRITE FUNCTION that prints ‘n’ names from the friendList on screen!
**for (int i = 0; i < n; i++)
{
cout << friendList[i] << " " << i << endl;
}**
}
void terminate(char* friendList[], int n)
{
// WRITE FUNCTION that releases all dynamically allocated memory!
**for (int i = 0; i < n; i++)
{
delete friendList[i];
}
delete [] friendList;
cout << "deleted! ";**
}

I see a few problems with this code:
In main():
not validating that cin.getline() is successful before using the contents of buff.
AMOUNT is the wrong size to use when allocating a new char[] to store in friends[]. The correct size should be either strlen(buff)+1 or cin.gcount().
In terminate() (not to be confused with std::terminate()):
delete[]'ing the input array itself, which was not allocated with new[] to begin with and thus must not be delete[]'ed.

Instead of this statement
friends[count] = new char[AMOUNT];
you need to write
friends[count] = new char[strlen( buff ) + 1];
Pay attention to that the array friends itself is not allocated dynamically. But each its element points to a dynamically allocated array. So the function terminate can look like
void terminate(char* friendList[], int n)
{
// WRITE FUNCTION that releases all dynamically allocated memory!
for (int i = 0; i < n; i++)
{
delete [] friendList[i];
friendList[i] = nullptr;
}
cout << "deleted! ";
}

Related

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
}

A global static array in C++

I've got something like this:
static int n = 0; // global static int
int *arr = new int[n]; // global int*
int randToArray(int arr[], int min, int max) {
srand(time(NULL));
for(int i = 0; i <= n; i++) {
arr[i] = (rand() % max + min);
}
}
void printArray() {
if(n) {
for(int i = 0; i < n; i++)
cout << arr[i] << endl;
} else
cout << "The array hasn't been drawed yet.";
}
And then in the main function I have a menu with a switch and options for getting random numbers and printing the array:
switch(option) {
case 1:
cout << "Set the size of the array: ";
cin >> n;
randToArray(arr, 1, 99);
break;
case 2:
printArray();
wait();
break;
}
I need my array to be available globally in order to use in several other functions.
Everything works except one thing: when I want to print the array I get working properly only 8 first elements. Then the terminal shows up some very large numbers.
That's because you use
static int n = 0;
then allocate memory for zero elements.
Change the line static int n = 256; for example, to allocate memory for 256 elements.
Or, if you read n after, allocate the memory AFTER you have read n. That is, declare the array globally first (technically a pointer), as int *arr;, then
arr = new int[n];
after cin >> n;
static is a much overloaded keyword.
The way you use it, it means translation-unit-local.
Also, you don't have any global array in your code, only a pointer initialized to point to the beginning of an allocation of 0 ints.
That allocation won't be changed if you later change n.

How to copy values from an array into a new one?

I've been trying to figure this out off and on for a week now and I keep running into problems.
My objective:
Write a function that allocates memory for an integer array. The function takes as an argument an integer pointer, the size of the array, and newSize to be allocated. The function returns a pointer to the allocated buffer. When the function is first called, the size will be zero and a new array will be created. If the function is called when the array size is greater than zero, a new array will be created and the contents of the old array will be copied into the new array. Your instructor has provided arrayBuilder.cpp as starter code for this programming challenge. In addition, Lab9_1.exe is the executable for this application which you can test.
The code:
#include <iostream>
using namespace std;
int * arrayBuilder(int * arr, int size, int newSize);
void showArray(int * arr, int size);
int main()
{
int * theArray = 0;
int i;
cout << "This program demonstrates an array builder function." << endl << endl;
// create the initial array. The initial size is zero and the requested size is 5.
theArray = arrayBuilder(theArray, 0, 5);
// show the array before values are added
cout << "theArray after first call to builder: " << endl;
showArray(theArray, 5);
// add some values to the array
for(int i = 0; i < 5; i++)
{
theArray[i] = i + 100;
}
// show the array with added values
cout << endl << "Some values stored in the array: " << endl;
showArray(theArray, 5);
// expand the size of the array. size is not the original size. newSize
// must be greater than size.
theArray = arrayBuilder(theArray, 5, 10);
// show the new array with the new size
cout << endl << "The new array: " << endl;
showArray(theArray, 10);
cout << endl;
delete [] theArray; // be sure to do this a1t the end of your program!
system("pause");
return 0;
}
/*
FUNCTION: arrayBuilder
INPUTS Pointer to an array. Size of the array. If size is zero, arr can be NULL.
Size of the new array.
OUTPUTS: Returns a pointer to allocated memory. If newSize is greater than size,
an array of newSize is allocated and the old array is copied into the new
array. Memory pointed to by the old array is deleted. All new elements
are initialized to zero.
*/
int * arrayBuilder(int * arr, int size, int newSize)
{
// TODO: Your code goes here
return NULL; // default return value. No memory allocated!
}
/*
FUNCTION: showArray
INPUTS: Pointer to an array. Size of the array. If size is zero, arr can be NULL.
OUTPUTS: Prints the contents of the array to the console.
*/
void showArray(int * arr, int size)
{
cout << "arr = ";
for(int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
My struggles: I cannot figure out how to switch "arr" and a temporary array's values.
int * arrayBuilder(int * arr, int size, int newSize)
{
// TODO: Your code goes here
int * temp = new int [newSize];
for (int i = size; i < newSize; i++)
{
*arr = *temp;
temp++;
}
return NULL; // default return value. No memory allocated!
}
another attempt while searching for answers:
int * arrayBuilder(int * arr, int size, int newSize)
{
// TODO: Your code goes here
int * temp = new int [newSize];
memcpy (temp, arr, size *sizeof(int));
// HINT: Design the function before writing it.
delete[] arr;
for (int i = size; i < newSize; i++)
{
temp[i] = i;
}
return NULL; // default return value. No memory allocated!
}
Basically my end goal is to have the answer look like this:
This program demonstrates an array builder function.
theArray after first call to the builder:
arr = 0 0 0 0 0
some values stored in the array:
arr = 100 101 102 103 104
the new array:
arr = 100 101 102 103 104 0 0 0 0 0
PROGRESS!! Its not crashing anymore :-) This is where I'm at now:
This program demonstrates an array builder function.
theArray after first call to builder:
arr = -842150451 0 0 0 0
Some values stored in the array:
arr = 100 101 102 103 104
The new array:
arr = -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -8
42150451 -842150451 -842150451 -842150451
Press any key to continue . . .
I'll keep tinkering and let everyone know if I hit a wall! Thanks again guys!
OKAY! finally got it to display properly:
This program demonstrates an array builder function.
theArray after first call to the builder:
arr = 0 0 0 0 0
some values stored in the array:
arr = 100 101 102 103 104
the new array:
arr = 100 101 102 103 104 0 0 0 0 0
This is what I did. I feel like I may have cheated in the second part when i put 0 values in for "temp". It was my understanding that i was going to take the data from the previous array and put it into the new one, and instead I just remade it. (So it will only work with this particular set of values [only 0's]). Is there a different way I can code the second part so it works universally with whatever values are thrown at it???
int * arrayBuilder(int * arr, int size, int newSize)
{
int i = size;
int * temp = new int [newSize];
// What if the size is 0?
if (size <= 0)
{
while (i < newSize)
{
temp[i] = 0;
i++;
}
}
// Assuming the size _isn't_ 0
else
{
// "a new array will be created" (good)
for (i = 0; i < newSize; i++)
{
// The contents of the "old" array (arr) will be
// copied into the "new" array (temp)
while (i < size)
{
temp[i] = arr[i];
i++;
}
while (i >= size && i < newSize)
{
temp[i] = 0;
i++;
}
// as a hint, you can address the elements in
// both arrays using the [] operator:
// arr[i]
// temp[i]
}
}
// "The function returns a pointer to the allocated buffer."
// So, NULL is wrong, what buffer did you allocate?
return temp; // default return value. No memory allocated!
}
Since you put forth some effort.
Write a function that allocates memory for an integer array.
The prototype for this function was provided for you:
int * arrayBuilder(int * arr, int size, int newSize);
The function takes as an argument an integer pointer, the size of the
array, and newSize to be allocated. The function returns a pointer to
the allocated buffer.
This says nothing about doing anything with the "old" (passed in) array, so we should assume it needs to be left alone.
When the function is first called, the size will be zero and a new
array will be created.
The above text is meaningless given the context. Feel free to tell your instructor I said so. If the size is zero, how do you know how many elements to allocate?
If the function is called when the array size is greater than zero, a
new array will be created and the contents of the old array will be
copied into the new array.
OK, now the guts of what needs to be done (you're so close)
int * arrayBuilder(int * arr, int size, int newSize)
{
// What if the size is 0?
// Assuming the size _isn't_ 0
// "a new array will be created" (good)
int * temp = new int [newSize];
for (int i = size; i < newSize; i++)
{
// The contents of the "old" array (arr) will be
// copied into the "new" array (temp)
// as a hint, you can address the elements in
// both arrays using the [] operator:
// arr[i]
// temp[i]
// something is wrong here...
*arr = *temp;
// you definitely _don't_ want to do this
temp++;
}
// "The function returns a pointer to the allocated buffer."
// So, NULL is wrong, what buffer did you allocate?
return NULL; // default return value. No memory allocated!
}
You already got the answer here:
memcpy (temp, arr, size *sizeof(int));
but you are making several other mistakes after that. Primarily, you need to return temp ; not return NULL ;
But also you don't need the loop after the delete arr[] ;
Also don't delete arr[] if size is zero.
This is horribly complex code. Programming is all about reducing complexity.
With that in mind, here’s a proper C++ solution:
std::vector<int> arr = {1, 2, 3, 4, 5};
std::vector<int> copy = arr;
That’s it. I hope this exemplifies why you should use the standard library (or other appropriate libraries) rather than re-inventing the wheel. From the code you’ve posted I am assuming that you’ve learned (or are learning) C++ from a horrible book or course. Trash that and get a proper book. C++ is complex enough as it is, no need to add needless complexity.
Just to help you realize why the first attempt didn't work:
*arr = *temp;
This is assigning a value to the old array, from the new array. That's backwards.
But it's just targeting the first value, *arr doesn't change. You increment *temp, but you also need to increment *arr. (Also, manual pointer manipulation like that horrifying and memcopy() is a lot better. But hey, this is for learning purposes, right?)
Also, think about that loop:
for (int i = size; i < newSize; i++)
That's iterating through once for each bit that newSize is bigger than size. But you're doing two things here. 1) Copying over data and 2) initializing the new data. That for loop you have is good for going over the new data, but it's not the loop you want for copying over the data you already have. That would go from zero to size, right?
And when you're done you need to return the address of the array you built.
return NULL; // default return value. No memory allocated!
That's just some dummy mock code. It's a placeholder by the teacher. It's part of the code you're supposed to change.
Per your update:
I feel like I may have cheated in the second part when i put 0 values in for "temp"
Well what else were you going to put in there? You DO copy over the old array data. Then you EXPAND the array. What goes into the new territory? Zero values as a default is perfectly valid.
Is there a different way I can code the second part so it works universally with whatever values are thrown at it???
Well yes, but you'd have to actually have something to throw at it. Your ArrayBuilder function could take in additional arguments, possibly as a variadic function, so it knows what values to put into the new fields. But your function declaration doesn't have that. All it does is make the array bigger.
Also, in your last edit you've got those two while loops that iterate through i inside of a for loop which also iterates through i. That'll work, but just so you know it's a bit... uncouth. It's the sort of thing that'll get you in trouble when things get more complicated.
You could do this instead:
for (i = 0; i < newSize; i++)
{
if(i < size)
{
temp[i] = arr[i];
}
else // if(i >= size && i < newSize) //Wait a sec, this "if" is superfluous. It's conditions are enforced the the first if and the loop condition.
{
temp[i] = 0;
}
}
You should also probably delete the comments that make it sound like someone else wrote your code for you. Because someone else did your homework for you. It's best to
Finally, THOU SHALT INDENT THY CODE!
If I have correctly understood the assignment the function should look the following way.
First of all I would substitute the function declaration
int * arrayBuilder(int * arr, int size, int newSize);
for
int * arrayBuilder( const int *arr, size_t size, size_t newSize );
Here is its definition
int * arrayBuilder( int * arr, int size, int newSize)
{
int *tmp = 0;
if ( newSize >= 0 )
{
tmp = new int[newSize] {};
int copy_size = std::min( size, newSize );
if ( copy_size > 0 ) std::copy( arr, arr + copy_size, tmp );
}
delete []arr;
return tmp;
}
Try this:
Code:
#include <iostream>
using namespace std;
int a[3] =
{
1,
2,
3
};
int b[3];
int main ()
{
cout << endl;
cout << "Array #1 elements: " << endl;
for(int i = 0; i < 3; ++i)
{
cout << a[i] << " ";
}
for(int i = 0; i < 3; ++i)
{
b[i] = a[i];
}
cout << endl << endl;
cout << "Copying Array #1 elements to Array #2..." << endl;
cout << endl;
cout << "Array #2 elements: " << endl;
for(int i = 0; i < 3; ++i)
{
cout << b[i] << " ";
}
cout << endl << endl;
return 0;
}

Printing a dynamic array after increasing its size

I'm currently making a code on the MU game using dynamic arrays, and I've got a problem with printing a sequence.
Rule: If the first character is denoted by the character M, and the rest of the sequence is denoted by R, then the new sequence is MRR.
Examples include:
Current sequence: MIUI
New sequence: MIUIIUI
Current sequence: MUM
New sequence: MUMUM
Current sequence: MU
New sequence: MUU
Here are snippets of my code:
IN MAIN:
if (userchoice == 2)
{
if (rule2valid == false)
{
cout << "This rule may not be applied to your input." << endl;
return 0;
}
int newsize = size + size - 1;
char *resultant = new char[newsize];
resultant = applyRule2(userinput, size);
printarray (resultant, newsize);
}
In the function which applies the rule:
char *applyRule2(char* sequence, int size)
{
int newsize = size + size - 1;
int j = 1;
char* applyRule = new char[newsize];
for (int i = 0; i < size; i++)
applyRule[i] = sequence[i];
for (int i = size; i < newsize; i++)
{
applyRule[i] == sequence[j];
}
return applyRule;
}
and the function for printing:
void printarray(char* sequence, int size)
{
for (int i = 0; i < size; i++){
cout << sequence[i] << "\t";
}
cout << "The length of this array is : " << size;
cout << endl;
}
The problem is that when I run the program, my output is as such:
Input: M U M
Output: M U M, The length of this string is 5. (supposed to be M U M U M)
Input: M I U I
Output: M I U I, the length of this string is 7. (supposed to be M I U I I U I)
What I have done so far is that I allocated a new dynamic array with the new size, and added values into the array accordingly. I am, however, at a loss as to whether the problem lies in the applyRule2 function or in the printarray function.
It would be greatly appreciated if someone could point me out in the right direction.
There are a few error in your code. As Alf says you really should use std::string. but anyway here are some of the errors.
for (int i = size; i < newsize; i++)
{
applyRule[i] == sequence[j];
}
should be
for (int i = size; i < newsize; i++)
{
applyRule[i] = sequence[j];
}
You had a double equals == when you should have written one equals =. Your compiler should have warned you about this, pay attention to compiler warnings.
Another error
char *resultant = new char[newsize];
resultant = applyRule2(userinput, size);
should be
char *resultant = applyRule2(userinput, size);
The code you have written allocates some memory and then on the very next line it throws away that memory and instead uses the memory you allocated in applyRule2. So this isn't actually a bug, but it is a waste of resources. Your program will never get back the wasted memory. This is called a memory leak.
just use std::string instead of raw arrays and raw pointers and new

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.