簡體   English   中英

我應該如何在C中實現rollDice()函數?

[英]How should I implement a rollDice() function in C?

我嘗試實現旨在將骰子擲出一定時間的功能。

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

int * rollDice(int len) //len = times the dice is rolled.
{
    int ints[len];

    int i = len-1;


    while(i>0)
    {

        ints[i--] = (rand()%6)+1;

    }

    return  ints;
}


int main(int argc, const char * argv[])
{


    int * ints = rollDice(10);

    for(int i =0; i<10; i+=1)
    {
        printf("%d ",*(ints+i));
    }
    return 0;
}

程序總是打印此內容,我的指針概念是否錯誤?

104 0 0 0 1919706998 2036950640 1667723631 1836545636 16 48 

你不可以做這個

return ints;

它在堆棧上聲明。 您需要使用足夠的內存傳遞它,或者使用malloc在函數中分配內存,然后將其傳遞回去。

int * rollDice(int len) //len = times the dice is rolled.
{
    int *ints = malloc(sizeof(int) * len);
    int i = len-1;
    while(i>0)
    {
        ints[i--] = (rand()%6)+1;
    }
    return  ints;
}

哈里的答案是正確的。 您無法返回局部變量的地址。 函數返回后,該變量即被銷毀。

不必在函數中分配內存,只需將要填充的數組傳遞給函數即可:

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

#define NUM_DICE    10

void rollDice(int *dice, int num_dice)
{
    int i;

    for (i = 0; i < num_dice; i++) {
        dice[i] = (rand() % 6) + 1;
    }
}


int main(int argc, const char * argv[])
{
    int dice[NUM_DICE];

    srand(time());     /* Don't forget this! */

    rollDice(&dice, NUM_DICE);

    for(int i = 0; i < NUM_DICE; i++)
    {
        printf("%d ", dice[i]);    /* Easier to use brackets than pointer arithmetic. */
    }

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM