sorting two-dimensions

how to sort two dimensional array of c-strings?

say we have the following variables:

1
2
char strings[200][10];
int number


where user inputs random words (200 being the max size of the input and 10 is the max size of each word)
where number is the number of each word occurs in the input


i thought it would be as simple as the following but boy was i wrong

1
2
3
4
5
6
7
8
9
10
for (int i = 0; i < number - 1; i++)
	{
		int min = i;
		for (int j = i + 1; j < number; j++)
			if (strings[j] < strings[min])
				min = j;
		string temp = strings[i];
		strings[i] = strings[min];
		strings[min] = temp;
	}


i guess above code only works for 1d array of strings, and i don't think we've touched on 2d arrays in class (let alone c-strings), and i couldnt find it in the chapter ;/
Well C-style char arrays,

> if (strings[j] < strings[min])
Look up strcmp()

> string temp = strings[i];
Look up strcpy()

Also, string isn't a native data type in C.

hi salem!

thanks for your reply!!

i reviewed those predefined functions, and i came up with the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
char strings[200][10];
int number = 0;

for (int i = 0; i < number; i++)
	{
		for (int j = 0; j < number; i++)
		{
			if (strcmp(strings[j], strings[j + 1]) > 0)
			{
				char temp[10];
				strcpy(temp, strings[j]);
				strcpy(strings[j], strings[j + 1]);
				strcpy(strings[j + 1], temp);
			}
		}
	}

is above code anywhere near correct?


Also, string isn't a native data type in C.

yes, i know. the homework consists of c-strings, strings, and vectors. i have to learn all three :'c
Last edited on
> is above code anywhere near correct?
Did you bother to test it before asking?

Sure, superficially, it seems like it's heading in the right direction.

But the real proof is compiling and testing the code.

conceptually what you have is a 1-d array of c-strings. the fact that the string itself is an array may be confusing you a little. Does this help you when thinking about it? Its the same as an array of ints, in that regard... only difference is the comparison function for the c-strings is a little wonky (c++ strings fix this). a 2-d array of strings is a 3-d char array, do you see this?
Last edited on
@gongong, if you compare using strcmp() then you will need only one loop. however if you compare by yourself then you need 2 loops.
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

int main ()
{    
    char st[3][10]={{'a','b','c','\0'},{'a','b','d','\0'},{'a','b','\0'}};
    for(auto x:st){
        cout<< x<<endl;    
    }
return 0;
}

output:
abc
abd
ab
Topic archived. No new replies allowed.