当我尝试将由 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("
");
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("
Flop %d = %p
", *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