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

当我尝试将由 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值