2014-02-28 92 views
0

我正在嘗試製作一個程序來跟蹤棒球卡的集合。我正在模擬購買7張卡片的包裝,並試圖完成整個系列(其中包含500張獨特的卡片)。要做到這一點,我假設每張卡都有一個0-499的值,並且我已經創建了一個函數來模擬每個包中包含唯一編號的7張卡的購買包。然而,該計劃似乎並沒有工作,並最終崩潰。一些幫助將不勝感激。下面是我的程序(這並不完全是尚未完成):陣列內的數組

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


int (*newDeck(int n)) //My function to generate a pack of 7 cards 
{ 
      int b[n]; 
      int *(deck); 
      deck = &b; 
      int rn; 


      for (int i = 0; i < 7; i++) 
      { 
       rn = rand(); 
       deck[i] = rn%500; 
      } 


     return deck; 
} 



int main() 
{ 

     int collection[500][2], *deck; 

     for (int i = 0; i < 500; i++) //Populating the array of the entire collection 
     { 
      collection[i][0] = i; 
      collection[1][1] = 0; 
     } 

     srand(time(NULL)); //Calling the function and filling it with random numbers 
     deck = *newDeck(7); 
     printf("%d\n", *newDeck(7)); 



     for (int i = 0; i < 7; i++) // Adding the numbers generated to the entire collection 
     { 
      (collection[deck[i]][1])++; 
     } 
    } 


return 0; //There's more to do but that's all I've done so far and it doesn't work 
} 
+1

我建議你拿起一個很好的C語言編程的書,並辦理指針和數組的章節.... – Recker

+0

是'} '返回0之前';輸入錯誤? – Littm

+0

當_crashes_時出現什麼錯誤? –

回答

0

newDeck()功能,更換

int b[n]; 

int *b = malloc(sizeof(int) * b); 

您當前的方法返回初始化甲板在調用newDeck()時分配給堆棧的內存。這個內存在函數返回時被拋棄。因此,爲了使這個工作起作用,你必須調用malloc(),這將永久地保留內存,直到你稍後調用指針的free() - 也許一旦你完成了對甲板的工作。

0

真的需要一本很好的C書,並仔細閱讀。

The Definitive C Book Guide and List的回答在書選上給出了一些非常好的建議,special this answer

無論如何,這裏是你的代碼的修訂版本:

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

int *newDeck(size_t n) 
{ 
    int *deck; 

    if ((deck = malloc(sizeof(int) * n)) == NULL) 
    { 
     perror("malloc"); 
     exit(EXIT_FAILURE); 
    } 

    srand(time(NULL)); 
    for (size_t i = 0; i < n; i++) 
    { 
     deck[i] = rand() % 500; 
    } 

    return deck; 
} 

int main() 
{ 
    int collection[500][2], *deck; 

    for (int i = 0; i < 500; i++) //Populating the array of the entire collection 
    { 
     collection[i][0] = i; 
     collection[i][1] = 0; 
    } 

    deck = newDeck(7); 
    for (int i = 0; i < 7; i++) 
    { 
     printf("%d\n", deck[i]); 
    } 

    for (int i = 0; i < 7; i++) // Adding the numbers generated to the entire collection 
    { 
     (collection[deck[i]][1])++; 
    } 

    free(deck); // Does not need deck anymore. 

    exit(EXIT_SUCCESS); 
}