Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

My median program has a segmentaion fault?

Status
Not open for further replies.

rego

Programmer
Apr 23, 2001
2
US
Hi:

I would like a little help with debugging this program.
I have ran it and the error message is printed at the botum(segmentation fault?). There may be several problems with the code.

Please help!



//This program will except numbers and return the median

#include <iostream.h>

int BubbleSort(int [], int);

int main()
{
int numgrades;
int nums[numgrades];
int i, sum, moves;

moves = BubbleSort(nums, numgrades);

cout << &quot;Enter the number of grades to be processed: &quot;;
cin >> numgrades;

int *grade = new int[numgrades]; //Create the array

for(i = 0; i < numgrades; i++)
{
cout << &quot;\bEnter a grade: &quot;;
cin >> grade;
}

cout << &quot;The sorted list is: &quot;;

for(i = 0; i < numgrades; i++)

cout << &quot; &quot; <<nums;
cout <<&quot;\n&quot; <<moves << &quot; were made\n&quot;;

return 0;
}

int BubbleSort(int num[], int numgrades)
{
int i, j, temp, numel, moves = 0;

for (i = 0; i < (numel - 1); i++)
{
for(j = 1; j < numel; j++)
{
if (num[j] < num[j-1])
{
temp = num[j];

num[j] = num[j-1];

num[j-1] = temp;

moves++;
}
}
}
}

int findmedian(int a[], int n)
{
int mid;

if(n%2 == 0)
mid =n/2;


else
mid =n/2 +1;

cout <<&quot;The median is: &quot;<<mid;
cout <<endl;

return a[mid];
}

python:~$ g++ median.cpp
python:~$ a.out
Segmentation fault
python:~$ exit
Script done on Tue Apr 24 23:50:02 2001

Thanks for any help provided
rego
 
your problem is happening because the values for numgrades & nums are not initialized. Also you are sorting before the user has entered any values.

try this:

int* nums;
int numgrades;

// user enters # of grades

nums = new int[numgrades];

// loop for user to enter grades

// call bubblesort

// and dont forget to do the following

delete nums;


Also, as an alternative, you could declare
const int MAX_GRADES = 256; and declare the array for nums using this rather then dynamically.

matt


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top