我正在尝试对二维数组进行排序。首先我按列排序,然后按行排序。逐列有效,但逐行无效。这段代码有什么问题?
int scmpr (const void *a, const void *b){
return strcmp((const char*)a, (const char*)b);
}
int main(void){
int i,j;
char **tab;
tab=(char**)malloc(sizeof(char*)* 10);
for(i=0; i<10; i++){
tab[i]=(char*)malloc(sizeof(char)*15);
}
for(i=0; i<10; i++){
for(j=0; j<15; j++){
tab[i][j]=rand()%20+'b';
printf("%c ", tab[i][j]);
}
puts("");
}
for (i = 0; i<10; i++){
qsort(&tab[i][0], 15, sizeof(char), scmpr);
}
qsort(tab, 10, sizeof(char), scmpr); //<-- doesn't work
for(i=0; i<10; i++){
for(j=0; j<15; j++){
printf("%c ", tab[i][j]);
}
puts("");
}
puts("");
return 0;
}
最佳答案
我认为你的意思是以下内容
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define M 10
#define N 15
int ccmp( const void *lhs, const void *rhs )
{
unsigned char c1 = *( const unsigned char *)lhs;
unsigned char c2 = *( const unsigned char *)rhs;
if ( c1 < c2 ) return -1;
else if ( c2 < c1 ) return 1;
else return 0;
}
int scmp( const void *lhs, const void *rhs )
{
return strcmp( *( const char ** )lhs, *( const char ** )rhs );
}
int main( void )
{
char **tab;
tab = ( char** )malloc( M * sizeof( char* ) );
for ( size_t i = 0; i < M; i++ )
{
tab[i] = ( char* )malloc( N * sizeof( char ) );
}
srand( ( unsigned int )time( NULL ) );
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N - 1; j++ )
{
tab[i][j] = rand() % ( 'Z' - 'A' + 1 ) + 'A';
}
tab[i][N-1] = '\0';
}
for ( size_t i = 0; i < M; i++ )
{
printf( "%s\n", tab[i] );
}
printf( "\n" );
for ( size_t i = 0; i < M; i++ )
{
qsort( tab[i], N - 1, sizeof( char ), ccmp );
}
qsort( tab, M, sizeof( char * ), scmp );
for ( size_t i = 0; i < M; i++ )
{
printf( "%s\n", tab[i] );
}
printf( "\n" );
for ( size_t i = 0; i < M; i++ ) free( tab[i] );
free( tab );
return 0;
}
程序输出可能如下所示
DJSKLJOHGHEANW
ZSDZJZXCKGYOVF
LHEOQYAEHOLPYR
PLORDTQOSNQFVP
TQUEYAVQYVUHKH
WIZOVPHYKXPEMF
JHUFARLARGQSEN
BOWYYXOTMVTYUI
DIOOPKVPDHPXPI
PTXQJVQHTGCHDY
AAEFGHJLNQRRSU
ADEGHHJJKLNOSW
AEEHHLLOOPQRYY
AEHHKQQTUUVVYY
BIMOOTTUVWXYYY
CDFGJKOSVXYZZZ
CDGHHJPQQTTVXY
DDHIIKOOPPPPVX
DFLNOOPPQQRSTV
EFHIKMOPPVWXYZ
关于c - 使用 qsort 对 2D 数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31126462/