简体   繁体   中英

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

I try to implement a function meant to roll a dice a certain amount of time.

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

Program always prints this, is my conception of pointers false ?

104 0 0 0 1919706998 2036950640 1667723631 1836545636 16 48 

You cannot do this

return ints;

It's declared on the stack. You need to either pass it in with enough memory or allocated the memory in the function using malloc and pass it back.

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's answer is right; you can't return the address of a local variable. That variable is destroyed as soon as the function returns.

Instead of having to allocate memory in the function, just pass the array to be filled into the function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM