简体   繁体   中英

Problem while assigning random generated int to an array via a pointer in C

When I try to assign values generated by rand() to pointers there occur some problems.

When I assign random value to pointer, it shows correct value in rand_cards() function. But when I want to see results somewhere else, it shows different number. Be it in flop() function or main() .

Sometimes it shows correct value in flop() too, but wrong in main() .

What is the problem?

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

Here the outputs

One output:

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

Another output:

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

I would guess that you are overflowing card_exists , and this happens to overwrite your table_ranks .

Your card_exists has room for 12×4 elements, but both of your rand() lines potentially generate larger numbers. A way to randomly generate valid indices would be rand() % 12 and rand() % 4 (recall that the first index is 0), but you might just increase the array card_exists array size as needed.

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