数组中的数组

时间:2014-02-28 04:02:42

标签: c arrays function pointers

我正在尝试制作一个程序来跟踪棒球卡的集合。我正在模拟购买7张卡片,我正在尝试完成整个收集(其中包含500张独特的卡片)。要做到这一点,我假设每张卡都有一个0-499的值,我创建了一个模拟购买每包7个唯一编号的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
}

2 个答案:

答案 0 :(得分:0)

newDeck()功能中,替换

int b[n];

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

当前方法返回调用newDeck()时在堆栈中分配的内存中的初始化牌组。函数返回时,该内存将被丢弃。因此,要使其工作,您必须调用malloc(),它将永久保留内存,直到您稍后在指针上调用free() - 也许一旦您完成了使用套牌。

答案 1 :(得分: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);
}