Reputation: 489
i have following code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int comp(const void *a, const void *b){
char *const *aa=a;
char *const *bb=b;
return strcmp(*aa,*bb):
}
int main(int argc,char **argv){
int i;
qsort(argv+1,argc-1,sizeof *argv,comp);
for (i=1;i<argc;i++)
printf("i: %d==> '%s'\n",i,argv[i]);
return 0;
}
but here is errors
Error 1 error C2440: 'initializing' : cannot convert from 'const void *' to 'char *const *' c:\users\student\documents\visual studio 2008\projects\sort_argv\sort_argv\sort_argv.cpp 5 sort_argv
Error 2 error C2440: 'initializing' : cannot convert from 'const void *' to 'char *const *' c:\users\student\documents\visual studio 2008\projects\sort_argv\sort_argv\sort_argv.cpp 6 sort_argv
Error 3 error C2143: syntax error : missing ';' before ':'
c:\users\student\documents\visual studio 2008\projects\sort_argv\sort_argv\sort_argv.cpp 7 sort_argv
Error 4 error C2143: syntax error : missing ';' before ':'
c:\users\student\documents\visual studio 2008\projects\sort_argv\sort_argv\sort_argv.cpp 7 sort_argv
please help
Upvotes: 1
Views: 779
Reputation: 545598
In C++, use sort
instead of qsort
. Furthermore, the elements of (Apparently not true.)argv
must not be mutated since they are (implicitly, for C backwards compatibility) declared const
. Therefore, you need to copy them somewhere else:
#include <string>
#include <vector>
#include <algorithm> // for sort
int main(int argc, char const* argv[]) {
std::vector<std::string> args(argv, argv + argc);
std::sort(args.begin(), args.end());
}
(Notice that this solution uses string
and vector
instead of C strings and C-style arrays where possible. That’s not necessary but it makes the code much easier and shorter.)
Upvotes: 4
Reputation: 179849
Well, are you using C or C++ ? You've got a valid C program (minus the typo :
instead of ;
). Yet you name it ".cpp", and initially tagged the question only "C++" (fixed now). If you don't tell it otherwise, Visual Studio's compiler will compile ".cpp" files as C++. And your program is not valid C++.
In C++, you would use std::sort
, not qsort
. It has a different interface, and const void*
is not needed. Then your problem will disappear.
Upvotes: 4
Reputation: 37478
Try replacing:
int comp(const void *a, const void *b){
char *const *aa=a;
char *const *bb=b;
return strcmp(*aa,*bb):
}
with:
int comp(const void *a, const void *b){
const char* aa = (const char*)a;
const char* bb= (const char*)b;
return strcmp(*aa,*bb):
}
..to solve the pointer conversion problem.
Upvotes: 0
Reputation: 8298
I think your question is not well asked, and it shows that you didn't even read your code carefully before asking. However, one obvious mistake is that:
return strcmp(*aa,*bb): // : instead of ;
Upvotes: 2