使用qsort对字符串进行排序不起作用
Sorting strings with qsort does not work
我有一个程序,它会询问几个字符串并对它们进行排序。我的代码是:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX_STR_LEN 256
int myStrCmp (const void * a, const void * b)
{
return strcmp((const char *)a, (const char *)b);
}
int main(void)
{
int strNum; // expected number of input strings
int strCnt; // counter of strings
char ** storage; // pointr to the memory when strings are stored
char strBuf[ MAX_STR_LEN]; // buffer for strings
char * strPtr;
// input of strings number
do{
printf("How many strings will be entered: ");
while( scanf("%d", &strNum) != 1)
{
printf("ERROR: Not number was entered!n");
while( getchar() != 'n' );
printf("Please enter a number: ");
}
if( strNum < 2 )
{
printf("ERROR: Number less than 2 was entered!n");
}
while( getchar() != 'n' );
}
while(strNum < 2);
// allocation of memory for pointers
storage = (char **) calloc(strNum, sizeof(char*) );
if( storage == NULL )
{
printf("ERROR: Unexpected problems with memory allocation!n");
return 1;
}
// input of strings
for( strCnt = 0; strCnt < strNum; strCnt++)
{
printf("Enter string #%d:n", strCnt + 1);
fgets(strBuf, MAX_STR_LEN, stdin);
strPtr = strchr(strBuf, 'n');
if( strPtr )
{
*strPtr = ' ';
}
else
{
strBuf[ MAX_STR_LEN - 1] = ' ';
}
// allocation memory for particular string
storage[strCnt] = (char *) malloc(strlen(strBuf) + 1);
if(storage[strCnt] == NULL)
{
printf("ERROR: Unexpected problems with memory allocation!n");
return 2;
}
// move string to dynamic memory
strcpy(storage[strCnt], strBuf);
}
// sort the strings
qsort(storage, strNum, sizeof(char**), myStrCmp);
// output the result
printf("nSorted strings:n");
for( strCnt = 0; strCnt < strNum; strCnt++)
{
printf("%sn", storage[strCnt]);
}
return 0;
}
最简单的测试显示了问题:
How many strings will be entered: 3
Enter string #1:
ddd
Enter string #2:
aaa
Enter string #3:
ccc
Sorted strings:
ddd
aaa
ccc
我试过Visual C++和gcc,但结果是一样的。请告诉我代码出了什么问题?
问题出在myStrCmp
函数中。
因为a
和b
不是一个简单数组中的元素,而是指针数组中的,所以它们的类型必须是char **
,并且比较两个元素的函数必须如下:
int myStrCmp (const void * a, const void * b)
{
return strcmp(*(const char **)a, *(const char **)b);
}
相关文章:
- 尝试使用C++中的模板进行BST排序,但在使用随机字符串进行测试时不起作用
- 我的C++合并排序代码不起作用。我在这里错过了什么?
- 使用选择排序对数组数据结构进行排序,但它不起作用
- c++ 选择排序在特定情况下不起作用
- 排序不起作用 c++
- 在 C++ 中使用 10 个随机整数的数组进行气泡排序不起作用
- 插入排序不起作用
- 分而治之合并排序不起作用
- C 排序字符串的动态阵列 - 排序不起作用
- 为什么tha std :: list ::排序不起作用
- C++向量<Struct>排序不起作用
- 快速排序不起作用(分段错误)
- 使用qsort对字符串进行排序不起作用
- 自定义结构排序不起作用
- 为什么我的快速排序不起作用
- 简单std::排序不起作用
- 为什么泡沫排序不起作用
- std::矢量排序不起作用
- 对向量进行排序不起作用
- 为什么这个基数排序不起作用