954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Small problem with command line

The program sorts numbers in ascending order. If the user enters a "-r" in the command line, the program sorts the numbers in descending order.

The problem I'm having is that I can't get the **** program to read the if/else condition correctly. Maybe something wrong with my syntax? :evil:

#include <stdio.h>

#define SIZE 100
#define FLAG "-r"

void sort_asc(int *);
void sort_des(int *);
void prn_list(int *, char *);

int i, j, temp;
int main(int argc, char *argv[])
{
	int list[] = {90, 70, 50, 60, 30, 100, 80};

	if (argv[1] == FLAG)
		sort_des(list);
	else
		sort_asc(list);

	return 0;
}

void sort_asc(int *list)
{
	char state[] = {"ascending"};

	for (i = 0; i < 7; i++)
		for (j = i + 1; j < 7; j++)
			if (list[i] < list[j])
			{
				temp = list[i];
				list[i] = list[j];
				list[j] = temp;
			}

	prn_list(list, state);

}

void sort_des(int *list)
{
	char state[] = {"descending"};

	for (i = 0; i < 7; i++)
		for (j = i + 1; j < 7; j++)
			if (list[i] > list[j])
			{
				temp = list[i];
				list[i] = list[j];
				list[j] = temp;
			}

	prn_list(list, state);
}

void prn_list(int *list, char *state)
{
	int cnt;

	printf("Your list in %s order:\n", state);

	for (cnt = 0; cnt < 7; cnt++)
		printf("%d\n", list[cnt]);
}
degamer106
Junior Poster
131 posts since Mar 2006
Reputation Points: 10
Solved Threads: 0
 

You compare the contents of two strings with the strcmp function in the header. What you're actually doing with the == operator is comparing two memory addresses. Since the two strings are extremely unlikely to be located at the same address, your comparison will fail and the sort will always be in ascending order.

Include and change this:

if (argv[1] == FLAG)

to this:

if (strcmp(argv[1], FLAG) == 0)
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

:cry: Thanks you saved me :cry:

degamer106
Junior Poster
131 posts since Mar 2006
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You