ufo ufo - 2 months ago 7
C Question

C - Function with variable number of arguments and command line arguments

I need to sort

n
number of strings lexicographically that are arguments of a function with variable number of arguments. In
main
function, strings are read as command line arguments.

Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>

void sort(int n,...)
{
//store optional arguments (strings) to array arr
va_list args;
va_start(args,n);
char **arr=malloc(n * sizeof(char*));
int i;
for(i=0;i<n;i++)
arr[i]=malloc((strlen(va_arg(args,char*)) + 1) * sizeof(char));
va_end(args);

//store length of each string to lenArr
//find max length and store it to temp (for sorting)
va_list args;
va_start(args,n);
int *lenArr=calloc(n , sizeof(int));
for(i=0;i<n;i++)
{
lenArr[i]=strlen(va_arg(args,char*)) + 1;
}

int max=0;
for(i=0;i<n;i++)
{
if(lenArr[i] > lenArr[max])
max=i;
}
int maxLen;
maxLen=lenArr[max];
char *temp=calloc(maxLen * sizeof(char));
va_end(args);

//sort array arr lexicographically
int j,min;
for(i=0;i<n-1;i++)
{
for(min=i,j=i+1;j<n;j++)
if(strcmp(arr[j],arr[min]) < 0)
min=j;
if(min!=i)
{
strcpy(temp,arr[i]);
strcpy(arr[i],arr[j]);
strcpy(arr[j],temp);
}
}
}

int main(int argc,char **argv)
{
int n=3;
sort(n,argv[1],argv[2],argv[3]);//this works when n is pre-defined


return 0;
}


How to read
n
strings as command line arguments in
main
function and print them sorted?

Also, I am am getting an error in function
sort()
-
redeclaration of args with no linkage
.

Answer
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int cmp(const void *a, const void *b){
    return strcasecmp(*(char**)a, *(char**)b);
}

void sort(int n, char *str[n]){
    qsort(str, n, sizeof(char*), cmp);
}

int main(int argc, char *argv[]){
    sort(argc-1, argv+1);
    for(int i = 1; i < argc; ++i)
        puts(argv[i]);
    return 0;
}

Execution example:

>a.out a B c Z x y
a
B
c
x
y
Z