helloTHERE
helloTHERE

Reputation: 1

accessing values in a struct array

I am passing in an array into a function straightflush. I use a counting loop so i can get to all of the elements but for some reason, even tho the counter i increases, i get the value and suit for the first element of the array. Therefore, only my spadesCount increases as it always shows 4 for the value and spade for the suit.

struct card{
    int value;
    char suit;
};


int straightflush(struct card hand[], int n)
    {
        int clubsCount = 0;
        int diamondsCount = 0;
        int heartCount = 0;
        int spadesCount =0;
        int i;
        for(i=0; i<n; i++)
        {
            if (hand[i].suit == 'c')
            {
                clubsCount++;
            }
            else if (hand[i].suit == 'd')
            {
                diamondsCount++;
            }
            else if (hand[i].suit == 'h')
            {
                heartCount++;
            }
            else{
                spadesCount++;
            }
        }
    return 0;
    }

here is my main:

int main(){
    struct card hand1[] = {{4,'s'}, {9,'s'},{12,'c'},{11,'s'},{8,'s'},
        {6,'d'}, {3,'d'},{7,'s'},{10,'s'},{12,'d'}};
    printf ("%d\n", straightflush(hand1, 10));
}

Upvotes: 0

Views: 64

Answers (2)

Seronis
Seronis

Reputation: 76

You can use a debugger or add the following line before the return statement in straightflush() to prove that your counts are actually accurate.

printf("%d %d %d %d\n", clubsCount, diamondsCount, heartCount, spadesCount);

Your return value has nothing to do with the values you read thus the printf statement in your main() function is not printing the count of any thing, it is just printing 0 no matter what.

If you want the counts accessible outside of striaghtflush() you need to either use global variables for those counts (a generally shunned idea) or pass some values in by reference. An example of this would be:

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

void editValues( int *numDiamonds, int *numClubs, int *numHearts, int *numSpades ){
    *numDiamonds = 3;
    *numClubs = 5;
    *numHearts = 7;
    *numSpades = 11;
}

int main(int argc,char**argv)
{
    int numD=0, numC=1, numH=2, numS=3;
    printf("%d %d %d %d\n", numD, numC, numH, numS);
    editValues(&numD, &numC, &numH, &numS);
    printf("%d %d %d %d\n", numD, numC, numH, numS);
    return 0;
}

Upvotes: 1

Old Panda
Old Panda

Reputation: 1606

I just run your code and the four count variables have correct values. I think it's because you are returning 0 at the end of your straightflush function, the output is always 0.

Upvotes: 4

Related Questions