bubble sort with pointers.

So, as part of an excercise, we're writing programs where the only parameters allowed are pointers. I cannot get this bubble sort to work using pointers, however.

Any advice?

The error Im getting is:

"Unhandled exception at 0x0005518E in CSCI2010_Assignment3.exe: 0xC0000005: Access violation writing location 0x00000000."

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
using namespace std;

int readSize(int *);
int readArray(int *);
void sortArray(int *, int *);


int main() {
	int *integers = new int;
	int *array = new int;

	readSize(integers);
	*array = readArray(integers);		
	sortArray(array, integers);

	delete integers;
	delete [] array;

	system ("pause");
	return 0;
}

int readSize(int *integers) {
	cout << "How many integers are there? ";
	cin >> *integers;
	return *integers;
}

int readArray(int *integers) {
	int *array;
	array=new int[*integers];

	for (int i = 0; i < *integers; i++) {
		cout << "Please enter integer " << i + 1 << ": ";
		cin >> array[*integers]; }

	return *array;
	delete array;
}

void sortArray(int *array, int *integers) {
	int *temp = new int;
	bool *swap = new bool;

	do {
		swap = false;
		for (int i = 0; i <(*integers - 1); i++) {
			if (array[i] > array[i + 1]) {
				*temp = array[i];
				array[i] = array[i + 1];
				array[i + 1] = *temp;
				*swap = true;
			}
		}
	} while (swap);

	delete temp;
	delete swap;
}
You have quite a few problems. First you are overusing the new/delete calls. Just because the parameter will be a pointer doesn't mean you need to necessarily create the variable in your calling function as a pointer then use new.

Next I suggest you start printing out the values returned from your functions to insure that they are working correctly.

You may want to review your notes on both dynamic memory and more importantly your notes on functions.
Topic archived. No new replies allowed.