I have written a program which sorts command line arguments. However, when I am trying to print the output(using a function), I am not able to do it.Because I am trying to pass char *[] in a function which accepts char** as argument. After a lot of searching, which resulted in nothing much, I am hence here with my first question in SO.
#include "iostream"
#include "cstdlib"
#include "cstring"
using namespace std;
void sortArgs();
int stringcomp (const void * x, const void * y);
void parse(char **argv, int argc);
void printArgs();
void setArgs(char **argv, int argc);
int size;
char** argNew;
int main (int argc, char** argv)
{
parse(argv, argc);
printArgs();
return 0;
}
int stringcomp (const void *x, const void *y)
{
return strcmp (*(char * const *)x, *(char * const *)y);
}
void parse(char **argv, int argc)
{
setArgs(argv, argc);
sortArgs();
}
void setArgs(char **argv, int argc)
{
argNew=argv;
size=argc;
}
void printArgs()
{
char *s[size-1];
cout<<size<<endl;
for (int i = 1; i < size; i++)
{
s[i-1] = argNew[i];
}
for (int i = 0; i < size-1; i++)
cout<<" "<< s[i];
cout <<endl;
}
void sortArgs()
{
int i;
char *strings[size-1];
/* assign each argument to a pointer */
for (i = 1; i < size; i++)
{
strings[i-1] = argNew[i];
}
/* sort the array of pointers alphabetically with qsort */
qsort (strings, size - 1, sizeof *strings, stringcomp);
for (int i = 0; i < size-1; i++)
cout<<" "<< strings[i]; //this prints the output just fine
setArgs(strings, size); // pass the *strings[] here
}
I am trying to pass strings in the function- setArgs() from the function sort(). Later when I use it to print the array, it gives me seg fault. Can anyone please help me visualize/rectify the problem here ?
PS: I understand that I can print the char* strings[] in the sort method itself, but my main focus is how to pass it to a function which accepts char** as argument.