# Another C question (sorting arrays)

## Recommended Posts

Aiwendil    158
Hi again,

Sorry to be asking so many questions, but I have another problem.

I'm trying to write a program that takes command line parameters and sorts them, then does various operations on them. Everything works fine except for the sorting.

#include <stdio.h>#include <stdlib.h>float variance(char* data[], float average, int num);void swap(char *a, char *b);int main(int argc, char *argv[]){	int i;	float total = 0;	float mean = 0.0;	printf("Data: ");	for (i = 1; i < argc - 1; i++)	{		if (argv[i] > argv[i + 1])		{			swap(&argv[i], &argv[i + 1]);		}	}	for (i = 1; i < argc; i++)	{		printf("%s  ", argv[i]);	}		printf("\nMaximum: %s\n", argv[argc - 1]);	printf("Minimum: %s\n", argv[1]);	for (i = 1; i < argc; i++)		total += atoi(argv[i]);	mean = total / (argc - 1);	printf("Mean: %.2lf\n", mean);	printf("Variance: %.2lf\n", variance(argv, mean, argc));}float variance(char* data[], float average, int num){	float sum = 0.0;	int i;	for (i = 1; i < num; i++)	{		sum += (atoi(data[i]) - average) * (atoi(data[i]) - average);	}	return (sum / (num - 1));}void swap(char *a, char *b){	char tmp = *a;	*a = *b;	*b = tmp;}

I've also tried sorting inside main without using swap and a few other ways, but none of them really do anything.

What am I doing wrong?

Thanks

##### Share on other sites
Inside your swap function: try making char tmp a pointer and point to &a instead of just a.

##### Share on other sites
Aiwendil    158
I thought & was the address and * was the value. Either way, I tried it and it didn't work. Thanks for trying to help though.

##### Share on other sites
Noggs    141
The main issue you have with the sort is you are attempting to deal with command line parameters as if they are numerical. In actual fact argv is an array of pointers to character strings. I see you are using atoi() in the variance function - you need to extend that to the rest of the code.

What you probably want to do is loop over each argument and call atoi() on it to convert the string to an integer. You could use a std::vector<int> and push_back each integer into it. You can then use the vector as you are using argv. Now you only have to convert the arguments once.

The second problem with your sort is that you are doing a bubble sort but only passing over the array once. You need to pass over the array several times until you do not swap any values. The array will then be sorted.

There is of course lots of error checking you should do on your input data to ensure the user cannot break your program but that can wait!

##### Share on other sites
szecs    2990
for( i = 0; i < argc - 1; i++ ){   for( k = i+1; k < argc; k++ )   {      if (argv[i] > argv[k])      {          swap(&argv[i], &argv[k]);      }   }}