-5

I want to sort members of an array a[] with size s. I have firstly used a function to get the elements, and then another function to sort them in ascending order. The problem is in the sort function or in main or in both of them, because the execution of the program ends just after entering the data. Is there anyone here that can help me?

#include <iostream>
using namespace std;

void getdata() {
    int s;
    cin >> s;
    int a[s];

    for (int i=0; i<s; i++) {
        cin >> a[i];
    }
}

void sort(int a[], int s) {
    for (int i=0; i<s-1; i++) {
        for (int j=i+1; i<s; i++) {
            if (a[i] > a[j]) swap(a[i], a[j]);
        }
    }
}

int main () {
    int a[100],s;
    getdata();
    sort(a, s);
    return 0;
}
ajp15243
  • 7,704
  • 1
  • 32
  • 38
rt2000
  • 29
  • 2
  • 7

2 Answers2

1

You have a local definition of the array in your getdata() function:

void getdata() {
    int s;
    cin >> s;
    int a[s]; // <<<

It stays local there and has nothing to do with the array you declared in main:

int main () {
    int a[100],s; // <<<

You have to write your function such it takes these as parameters:

void getdata(int* a, int& s) {

    cin >> s;
    for (int i=0; i<s; i++) { // ...

and in main call

int main () {
    int a[100],s;
    getdata(a,s);
    sort(a, s);
    return 0;
}

UPDATE:

The condition in the inner for loop of your sort() function also looks pretty wrong, you probably meant j there not i:

for (int j=i+1; i<s; i++) {
             // ^    ^ 
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • it still stops after entering the data. – rt2000 May 08 '14 at 16:00
  • @rt2000 It fails after you enter the data? – Sev08 May 08 '14 at 16:06
  • @rt2000 There may be more flaws with your code. I'll leave it to you to find these. I would recommend using a debugger, or at least printing out some values for testing purpose. – πάντα ῥεῖ May 08 '14 at 16:08
  • @πάνταῥεῖ ῥεῖ, please could you suggest me any website,where I can understand more from this kind of topics? I don't know how to really interpret the debugging results. – rt2000 May 08 '14 at 16:17
  • @rt2000 _'I don't know how to really interpret the debugging results.'_ I don't understand this question? Just step through your program line by line, set breakpoints where you want to stop and check the current variable values when excecution is suspended. I you don't feel able to do this, just print out variables and marker messages at the points of interest for you. (to get you started: http://stackoverflow.com/questions/2069367/how-to-debug-using-gdb) – πάντα ῥεῖ May 08 '14 at 17:17
0

Always use std::vector if you have no definite advantage by using an array (and, in C++11, use std::array if s is known by compile time).

#include<vector>
#include<algorithm>

std::vector<int> a;
//fill it, then
std::sort(a.begin(),a.end());
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
davidhigh
  • 14,652
  • 2
  • 44
  • 75