-1

I looked everywhere and I could not find a concrete answer that suits my needs. I want use this type of format to sort a more complicated array than this example. It compiles, but when I run it I get the terminated by signal SIGSEV (address boundary error).

A simple example of what I am trying to do:

string array[] = {zipper, bad, dog, apple, car};
string temparray[5];
int counter = 0;

for(int i = 0; i < 5; i++){
       for(int x = 0; x < 5; x++){
            if(array[i] > array[x]){
              counter++;
            }
        }
       temparray[counter] = array[i];
}

for(int y = 0; y < 5; y++){
       array[y] = temparray[y];   
}

What seems to be the problem?

zx485
  • 28,498
  • 28
  • 50
  • 59
  • `temparray[counter]` with `counter >= 5`. you may have wanted `int counter = 0;` in the first loop. – Jarod42 Feb 29 '16 at 23:31
  • `counter` will be 5 or greater, I would guess. Run the program under `gdb` or whatever to debug. – Ken Y-N Feb 29 '16 at 23:31
  • Jarod42 you where spot on seeing that counter was supposed to be inside the first for loop so it resets with every iteration. thank you very much – Carlos J. Feb 29 '16 at 23:38
  • This is probably an exercise, but in real world you should seriously use `std::vector` and `std::sort`. See also [this answer](http://stackoverflow.com/a/2758095/620382) – Zulan Mar 01 '16 at 09:33

1 Answers1

0

You never reset counter. Suppose that your array is {5,4,3,2,1}. Then after the first iteration of the for loop, you'd have counter=4. After the next iteration of the inner for loop, counter would be 7, and you'd be trying to access the 7th element in temparray on your line

temparray[counter] = array[i];

but temparray is only 5 elements long. I don't offhand know how the > and < operators work for std::string's, but I'd bet oaks to acorns this is your problem.

You can fix this just by adding

counter=0;

directly after the aforementioned line:

temparray[counter] = array[i];

or by initializing it to zero at the start of the loop, or declaring it in the loop or what have you.

ocket8888
  • 1,060
  • 12
  • 31