#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    101
    Rep Power
    0

    Qsort is really confusing me.


    Code:
    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    
    int compare(const void *a,const void *b)
    {
    	char *x = (char *)a;
    	char *y = (char *)b;
    	return strcmp(x,y);
    
    }
    
    int compareTwo(const void *a,const void *b)
    {
    	int *x = (int *)a;
    	int *y = (int *)b;
    	return *x - *y;
    }
    int main()
    {
    	int iterate = 0;
    	char list[] = {'a','z','b','e','n'};
    	char nums[] = {67,56,45,78,56};
    	qsort(list,sizeof(list),1,compare);
    	qsort(nums,sizeof(nums) /4,4,compareTwo);
    	printf("%s\n\n",list);
    	for(iterate;iterate < 5;iterate++)
    	{
    		printf("%d\n",nums[iterate]);
    	}
    	getchar();
    	return 0;
    }
    The characters go in order but the integers don't. I used the same pointer structure for the chars data for the integer data and it doesn't go in order from least to greatest.

    Can someone tell me why the characters go in order but the integers don't?
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,379
    Rep Power
    1871
    > qsort(nums,sizeof(nums) /4,4,compareTwo);
    Use sizeof(int) instead of 4.

    > char nums[] = {67,56,45,78,56};
    Use int instead of char
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2012
    Posts
    83
    Rep Power
    39
    Don't use strcmp to compare characters. strcmp is expecting pointers to strings (that is a 0-terminated sequence of characters), not to single characters. If the characters happen to be equal, it will look at the next character in the array, which isn't the behaviour you want and which might cause undefined behaviour if this causes it to go outside of the bounds of the array (since the array is not 0-terminated).

IMN logo majestic logo threadwatch logo seochat tools logo