简体   繁体   中英

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

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.

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

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