2
當我使用add_card運行添加卡時,第7張卡應該對所有卡進行分類。但是當我運行這個時,我得到了一個半序的結果。爲什麼我的qsort結果不正確?
>> require 'ext/straight_count' #=> true >> s = EV::StraightCount.new; s.add_card(5,0); s.add_card(8,1); s.add_card(12,2); s.add_card(14,3); s.add_card(12,4); s.add_card(3,5); s.add_card(5,6)
card: 12
card: 5
card: 12
card: 14
card: 8
card: 5
card: 3
我不認爲NUM2INT有問題,因爲當我將數組打印回無序時,它會按預期方式出現。
straight.h
int *pCards, *pSortedCards;
int cCards[NUM_CARDS], cSortedCards[NUM_CARDS];
straight.c
void Init_straight()
{
pCards = &cCards[0];
}
static VALUE
add_card(VALUE self, int rCardValue, int rCardIndex)
{
*(pCards + NUM2INT(rCardIndex)) = NUM2INT(rCardValue);
if (NUM2INT(rCardIndex) == 6)
check_for_straight();
return Qnil;
}
check_for_straight()
{
sort_by_value(pCards);
}
card_sort.c
int compare_card_values (const void *a, const void *b)
{
const double *da = (const double *) a;
const double *db = (const double *) b;
return (*da > *db) - (*da < *db);
}
void sort_by_value(int *pCards)
{
qsort(pCards, NUM_CARDS, sizeof(pCards[0]), compare_card_values);
}