我应该如何在 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;
}

Harry的回答是正确的;你不能 return 局部变量的地址。该变量在函数 returns.

后立即被销毁

不必在函数中分配内存,只需将要填充的数组传入函数即可:

#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;
}