在C语言中通过指针将随机生成的int赋值给数组时出现的问题。

问题描述 投票:0回答:1

当我尝试将由 rand() 指针上出现了一些问题。

当我给指针分配随机值时,它在 rand_cards() 函数。但当我想在其他地方看到结果时,它显示的是不同的数字。无论是在 flop() 功能或 main().

有时,它显示正确的值在 flop() 错在 main().

问题出在哪里?

bool card_exists[12][4] = {false};

int table_ranks[5] = {0};
int table_aces[5] = {0};

// We will use these addresses to store random numbers in arrays above.
int *table_ranks_pos = table_ranks; 
int *table_aces_pos = table_aces;

int main(void) {

    srand((unsigned) time(NULL));

    flop();

    // Printing all elements of table_ranks
    for (int i = 0; i < 3; i++)
        printf("%d ", table_ranks[i]);
    printf("\n");

    return 0;
}

void flop() {
    while (table_ranks_pos < table_ranks+3 && table_aces_pos < table_aces+3) {

        rand_cards(table_ranks_pos, table_aces_pos); // Passing addresses as parameters

        // Printing value of address which we used previously
        printf("\nFlop %d = %p\n\n", *table_ranks_pos, table_ranks_pos);

        table_ranks_pos++;
        table_aces_pos++;

    }
}

void rand_cards(int *rank_addr, int *ace_addr) {
    int rand_rank, rand_ace;

    do {
        rand_rank = rand()%13+2;
        rand_ace = rand()%4+1;

        if (!card_exists[rand_rank][rand_ace]) {
            *rank_addr = rand_rank;
            printf("Rand %d = %d = %d = %p = %p = ", rand_rank, *rank_addr, *table_ranks_pos, rank_addr, table_ranks_pos);
        }

    } while (card_exists[rand_rank][rand_ace]);

    card_exists[rand_rank][rand_ace] = true;
}

这里的输出

一项产出。

Rand 10 = 10 = 10 = 0x559220064070 = 0x559220064070 = 
Flop 10 = 0x559220064070

Rand 2 = 2 = 2 = 0x559220064074 = 0x559220064074 = 
Flop 2 = 0x559220064074

Rand 13 = 13 = 13 = 0x559220064078 = 0x559220064078 = 
Flop 13 = 0x559220064078

10 16777218 13

另一个输出:

Rand 7 = 7 = 7 = 0x55966e907070 = 0x55966e907070 = 
Flop 7 = 0x55966e907070

Rand 13 = 13 = 13 = 0x55966e907074 = 0x55966e907074 = 
Flop 16777229 = 0x55966e907074

Rand 8 = 8 = 8 = 0x55966e907078 = 0x55966e907078 = 
Flop 8 = 0x55966e907078

7 16777229 8
c pointers random random-seed
1个回答
0
投票

我猜测你是溢出了 card_exists,而这恰好覆盖了你的 table_ranks.

您的 card_exists 有12×4元素的空间,但你的两个 rand() 行可能会产生更大的数字。随机生成有效指数的方法是 rand() % 12rand() % 4 (记得第一个索引是0),但你可以只增加数组的 card_exists 根据需要的数组大小。

© www.soinside.com 2019 - 2024. All rights reserved.