qsort i tablica struktur

0

Mam następujący kod, w którym w tablicy przechowuję struktury:

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

typedef struct Cos
{
	short val;
	short num;
} Cos;

int compare_cos(const void * a, const void * b)
{
	short v1 = ((Cos*)a)->val;
	short v2 = ((Cos*)b)->val;
	printf("%hd <> %hd \n", v1, v2);
	if ( v1 <  v2 ) return 1;
	if ( v1 == v2 ) return 0;
	if ( v1 >  v2 ) return -1;
}

int main(int argc, char const *argv[])
{
	Cos *tab[10];
	for (int i = 0; i < 10; ++i)
	{
		Cos *c = malloc(sizeof(Cos));
		c->val = (short)i + 1;
		c->num = (short)i + 1;
		tab[i] = c;
		printf("%hd %hd\n", c->val, c->num);
	}
	printf("\nSORTOWANIE:\n");
	qsort(&tab, 10, sizeof(Cos), compare_cos);

	// for (int i = 0; i < 10; ++i)
	// {
	// 	printf("%hi %hi\n", tab[i]->val, tab[i]->num);
	// }

	return 0;
}

Program ma posortować daną tablicę malejąco, względem pola val struktury Cos.
Jednak wyjście programu wygląda następująco:

1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10

SORTOWANIE:
12296 <> 12312 
12344 <> 12360 
12328 <> 12360 
12328 <> 12344 
12312 <> 12360 
12312 <> 12344 
12312 <> 12328 
12376 <> 12392 
12424 <> 12440 
12408 <> 12440 
12408 <> 12424 
12392 <> 12440 
12392 <> 12424 
12392 <> 12408 
12360 <> 12440 
12360 <> 12424 
12360 <> 12408 
12360 <> 12392 
12360 <> 12376

Najpierw drukuję tablicę w postaci początkowej, tutaj ok. Kiedy drukuję wartości porównywane w funkcji compare_cos drukowane są jakieś dziwne liczby.
Czy ktoś może to wyjaśnić i/lub poprawić program?

Program kompiluję na 32 bity:

gcc sort.c -std=c99 -m32
1
#include <stdio.h>
#include <stdlib.h>
 
typedef struct Cos { short val,num; } Cos;
 
int compare_cos(const void * a, const void * b)
  {
   short A=(*((Cos**)a))->val,B=(*((Cos**)b))->val;
   printf("%hd <> %hd \n",A,B);
   return (A<B)-(B<A);
  }
 
int main(int argc, char const *argv[])
  {
   int i;
   Cos *tab[10];
   for(i=0;i<10; ++i)
     {
      Cos *c=malloc(sizeof(Cos));
      c->val=i+1;
      c->num=i+1;
      tab[i]=c;
      printf("%hd %hd\n",c->val,c->num);
     }
   printf("\nSORTOWANIE:\n");
   qsort(tab,10,sizeof(Cos),compare_cos);
   for(i=0;i<10;++i) printf("%hi %hi\n",tab[i]->val,tab[i]->num);
   return 0;
  }

http://ideone.com/7JehtN

0

Pozostaje mi tylko podziękować. Dziękuję ;)

1 użytkowników online, w tym zalogowanych: 0, gości: 1