tags:

views:

48

answers:

2

i have implement this code from programming pearls and i think it should be correct but it gives me this mistake code:

#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;
}

mistake:

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 ==========

i think jon bentley should know such kind of topic yes why is such kind of mistake?

+5  A: 

Your charcmp function needs to take const void* parameters:

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

The error message:

cannot convert parameter 4 from 'int (__cdecl *)(char *,char *)' to 'int (__cdecl *)(const void *,const void *)'

is telling you that the argument you are passing (a pointer to the function charcmp) does not have the correct type to be passed into qsort.

Since this question is tagged as C++, you might consider using std::sort instead; it is type safe and much easier to use:

std::sort(sig, sig + strlen(sig));
James McNellis
+2  A: 

The error to lookout is

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

The function expects arguments of type const void*.

Prabhu Jayaraman