01001000 01101001
01001000 01101001

Reputation: 141

Undesired output in simple 2D array program

As a homework problem, I have to create a simple program that outputs 5 distinct cards from a standard 52 card deck.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>

void deal(char input_array[5][4]);

char deck[52][4]={"AcS","02S","03S","04S","05S","06S","07S","08S","09S","10S","JaS","QuS","KiS",
"AcH","02H","03H","04H","05H","06H","07H","08H","09H","10H","JaH","QuH","KiH","AcD","02D",
"03D","04D","05D","06D","07D","08D","09D","10D","JaD","QuD","KiD","AcC","02C","03C","04C",
"05C","06C","07C","08C","09C","10C","JaC","QuC","KiC"};

main()
{
    int index;
    char hand[5][4];
    deal(hand);

    for(index = 0; index < 5; index++){
        printf("%s\n", hand[index]);
    }
}

void deal(char input_array[5][4])
{
    int i, j, randInt, count = 0;
    //srand((unsigned int)time(NULL));
    srand(time(NULL));

    /* outer for loop used to assign 5 cards to array */
    for (i = 0; i < 5; i++){

        /* random int generated between 0 and 51, so a random card can be picked from the deck array */
        randInt = (rand() % 52);

        /* inner for loop checks each time whether the card already exists in the input_array. if it exists, count is incremented by 1 */
        for(j = 0; j < 5; j++){

            if(strcmp(input_array[j], deck[randInt]) == 0){
                ++count;
            }

        }

        /* after exiting inner for loop, if count is still 0, the card chosen from the deck isn't already in input_array. so it's added to input_array */
        if(count == 0){
            strcpy(input_array[i], deck[randInt]);
        }

    }
}

But once I run it over and over enough times, eventually I get weird/unexpected/random values (see images of output below).

https://i.sstatic.net/bZmdB.jpg

https://i.sstatic.net/QNPGt.jpg

I've gone through every line of code and double checked everything. I have no idea what's going wrong here. Any help is appreciated.

Upvotes: 1

Views: 62

Answers (1)

Spikatrix
Spikatrix

Reputation: 20244

Your code exhibits Undefined Behavior here:

if(strcmp(input_array[j], deck [randInt]) == 0){

Because input_array isn't initialized and contains "garbage" values.

To fix it, change

for(j = 0; j < 5; j++){

To

for(j = i-1; j >= 0; j--){

Also add append an else part:

if(count == 0){
         strcpy(input_array[i], deck [randInt]);
     }
else{
         input_array[i][0]='\0';
     }

input_array[i][0]='\0'; is done to NUL-terminate input_array[i] so that it gets initialized and the printf in main does not print wierd things.

Upvotes: 1

Related Questions