Hi, I am writing a code to sort a list of C-strings in a 2-D array. I'm a beginner and it isn't working out. The program crashes every time. After running a bit of testing, I found that the for loop in my sort function is not incrementing the variable "indexy" properly. It starts at 0, goes to one, then jumps to 1400000s, and the program crashes after. Can someone help me decipher what is wrong?
The "cout" at the function is to decipher the value of indexy, and that made me discover where it is crashing, I cannot however, understand why.

#include <cstdlib>
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;

int indexSmallest(char [][5], int, int);
void swap(char[][5], int, int);
void sort(char[][5], int);
int main(){
	char a[3][5] = {'b','b','c','d','\0',
					'a','b','d','c','\0',
					'a','a','a','c','\0'};
	sort (a, 3);
	for(int b=0;b<3;b++)
	cout << a[b] << endl;
}

int indexSmallest(char arr[][5], int start, int size){
	int indexMin, tempIndex, index = 0;
	char low[1][4];
	for(int count =0;count<5;count++){
		low[0][count] = arr[start][count];
	}
	for (index=start+1;index<size;index++){
		if(strcmp(low[0],arr[index])>0){
			for(int count =0;count<5;count++){
				low[0][count] = arr[index][count];
			}
			tempIndex = index;
			indexMin = tempIndex;
		}
	}
	return indexMin;
}


void sort(char arr[][5], int size){
	int indexy, indexSmall=0;
	for(indexy=0;indexy<size-1;indexy++){
		cout << "index passed is " << indexy;
		indexSmall = indexSmallest(arr, indexy, size);
		swap(arr, indexy, indexSmall);
	}
}

void swap(char arr[][5], int index, int indexSmall){
	char temp[1][5];
	for(int count=0;count<5;count++){
		temp[0][count] = arr[index][count];
	}
	for(int count = 0; count<5; count++){
		arr[index][count] = arr[indexSmall][count];
	}
	for(int count = 0; count < 5; count ++){
		arr[indexSmall][count] = temp[0][count];
	}
}

Recommended Answers

All 3 Replies

Why not just set up a standard sort and use strcmp() ?

for i = 0 to MAX-1
  for j = MAX-1 to i+1 by -1
    strcmp(array[j-1], array[j]))
       swap if needed

Why not just set up a standard sort and use strcmp() ?

for i = 0 to MAX-1
  for j = MAX-1 to i+1 by -1
    strcmp(array[j-1], array[j]))
       swap if needed

Hi, thanks for the reply, I'm new at this so I'm not sure what a standard sort looks like.

As for the strcmp function, how do I compare a 2 dimension variable with it? Do I only use the first dimension?

What WaltP gave you is a version of Bubble Sort. You can find many explanations and references on the 'net.

To compare one string in your array to another, yes, you use only the first index. As in

order = strcmp( arr[j], arr[j+1];
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.