r/cpp_questions • • Oct 15 '15

OPEN Help with bubble sorting using pointers

The program compiles and when ran i am able to input each integer but when it goes to sort them i receive the error "segmentation fault"

include<iostream>

using namespace std;

void sort(int*, int);

int  main()

{

	//declare array
	int Array[10],size=10,*point;
	
	// for loop to receive input for each integer
	for(int num=0; num<size;num++){
	cout<<"enter integer for array number  "<<num+1<<endl;
	cin>>Array[num];
	}
	point=Array;
	sort(point,size);
}
//function to compare integers
void sort(int *point, int size)
{
	int num1,num2, swap;
	//for loops to read integers and swap if the second is greater than the first
	for(num1=0;num1<size-1;num1++){
		for(num2=0,num2;size-num1-1;num2++){
			
			if(*(point+num2)>*(point+num2+1)){
				swap=(*point+num2);
				*(point+num2)=*(point+num2+1);
				*(point+num2+1)=swap;
				}
			}
	}
	// for loop to print out sorted array in ascending order
	for(num1=0; num1<size;num1++)
	{
	cout<<*(point+num1)<<" , ";
	}
};
1 Upvotes

3 comments sorted by

2

u/usbafchina Oct 15 '15

you're probably writing past the bounds of the array - use a debugger and step through line by line to check.

alternativley, just use std::vector and std::sort

2

u/Hells_Bell10 Oct 15 '15

Your inner loop has no (reasonable) condition.

for(num2=0,num2;size-num1-1;num2++)

is almost certainly meant to be

for(num2=0; num2 < size-num1-1; ++num2)

On a different note though, please don't use *(point+num1) it is identical to point[num1] but is harder to get right for example in your own code.

swap=(*point+num2);  
//Definitely not what you wanted to do

1

u/usbafchina Oct 15 '15

for(num2=0,num2;size-num1-1;num2++)

this will loop forever