【问题标题】:question about qsort implementation关于 qsort 实现的问题
【发布时间】:2011-03-20 13:23:15
【问题描述】:

我已经从编程珍珠中实现了这段代码,我认为它应该是正确的,但它给了我这个错误 代码:

#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
using std::qsort;
int charcmp(char*x,char *y){   return *x-*y;}
#define wordmax 100
int main(void){
    char word[wordmax];
    char sig[wordmax];
    while(scanf("%s",word)!=EOF){
        strcpy(sig,word);
        qsort(sig,strlen(sig),sizeof(char),charcmp);
        printf("%s %s\n",sig,word);
    }


     return 0;
}

错误:

1>------ Build started: Project: anagrams, Configuration: Debug Win32 ------
1>  anagrams.cpp
1>c:\users\david\documents\visual studio 2010\projects\anagrams\anagrams.cpp(11): warning C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1>          c:\program files\microsoft visual studio 10.0\vc\include\stdio.h(304) : see declaration of 'scanf'
1>c:\users\david\documents\visual studio 2010\projects\anagrams\anagrams.cpp(13): error C2664: 'qsort' : cannot convert parameter 4 from 'int (__cdecl *)(char *,char *)' to 'int (__cdecl *)(const void *,const void *)'
1>          None of the functions with this name in scope match the target type
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

我认为乔恩·宾利应该知道这样的话题是的,为什么会出现这样的错误?

【问题讨论】:

  • 错误信息相当清楚:“无法将参数 4 从 'int (__cdecl *)(char *,char *)' 转换为 'int (__cdecl *)(const void *,const void * )'"。您是否查看过该参数所期望的值的类型?

标签: c++


【解决方案1】:

你的charcmp函数需要带const void*参数:

int charcmp(const void* x, const void* y)
{   
    return *(const char*)x - *(const char*)y;
}

错误信息:

无法将参数 4 从 'int (__cdecl *)(char *,char *)' 转换为 'int (__cdecl *)(const void *,const void *)'

告诉你你传递的参数(一个指向函数charcmp的指针)没有正确的类型来传递给qsort

由于这个问题被标记为 C++,您可以考虑改用std::sort;它是类型安全且更易于使用的:

std::sort(sig, sig + strlen(sig));

【讨论】:

    【解决方案2】:

    要注意的错误是

    int (__cdecl *)(char *,char *)' to 'int (__cdecl *)(const void *,const void *)'
    

    该函数需要 const void* 类型的参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-03
      • 1970-01-01
      • 2011-03-30
      • 2021-03-03
      • 2012-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多