2014-03-04 45 views
0

我試圖將數組傳遞給一個函數並用信息填充它。這段代碼是從練習中學習C的按位運算的基礎,但是當數組被解析爲函數「filldeck」時,數組「甲板」變成了破壞。直到那裏它按預期工作。數組內容消失

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

typedef unsigned char card; 
typedef unsigned char pairs; 

/* arrays for the names of things */ 
static char *suits[] = {"Hearts","Diamonds","Clubs","Spades"}; 
static char *values[]= {"Ace","Two","Three","Four","Five","Six",\ 
        "Seven","Eight","Nine","Ten","Jack",\ 
        "Queen","King"}; 
static char *colour[]= {"Black","Red"}; 

/* function prototypes */ 
void printcard(card c); /* Displays the value of a card*/ 

void printdeck(card deck[52]); /* prints an entire deck of cards*/ 

void filldeck(card deck[52]); /* Populates a deck of cards */ 

void shuffle(card deck[52]); /* Randomizes the order of cards */ 

int compareface(const void* c1,const void *c2); 
/* compares the face value of 2 cards, suitable to pass to qsort 
as the fourth argument */ 

pairs findpairs(card *hand); /* finds any pairs in a hand */ 

int main() 
{ 
    card deck[52],*deckp; 
    card hands[5][5],handssorted[5][5]; 
    pairs numpairs[5],highest; 
    int hand,cd,winner; 

    srand(time(NULL));  /* seed the random number generator */ 

    /*populate and shuffle the deck */ 

    filldeck(deck); 
    scanf("%*c*"); 
    printdeck(deck); 
    scanf("%*c"); 
    shuffle(deck); 
    printdeck(deck); 
} 


void filldeck(card deck[52]) 
{ 
    /* populate the deck here */ 
    int x = 0; 
    //hearts 
    for(int y = 64; y <=112;y += 4) 
    { 
     deck[0 + x] = y; 
     x ++; 
    } 
    //diamonds 
    for(int y = 1; y <=49;y += 4) 
    { 
     deck[0 + x] = y; 
     x ++; 
    } 
    //clubs 
    for(int y = 2; y <=50;y += 4) 
    { 
     deck[0 + x] = y; 
     x ++; 
    } 
    //spades 
    for(int y = 67; y <=115;y += 4) 
    { 
     deck[0 + x] = y; 
     x ++; 
    } 
    printf("Deck filled"); 
    return; 
} 
+0

編譯所有警告和調試信息(例如'gcc -Wall -g')。學習使用調試器(例如'gdb')。 –

+0

爲什麼寫'0 + x'?結果將始終是'x'。 –

+0

「腐敗」是什麼意思? – Loghorn

回答

0

功能filldeck()增量x超出51和使用它來索引deck[52]。這樣,你超越了數組邊界並調用未定義的行爲