Home > database >  I'm getting an error message in line 11 near deck[i][j]
I'm getting an error message in line 11 near deck[i][j]

Time:04-02

I'm getting the following error message in 9th line of code (deck[i][j] = ...) invalid operands to binary (have ‘char *’ and ‘char *’). How can I fix this?

#include <stdio.h>

char* suit[4] = {"Hearts", "Diamonds", "Clubs", "Spades"};
char* face[13] = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", 
"Ten", "Jack", "Queen", "King"};

 char* deck[4][13];

void initialiseDeck(){
for(int i = 0; i < 4;   i)
    for(int j = 0; j < 13;   j)
        deck[i][j] = face[j]   "of"   suit[i];
}

void display(){
for(int i = 0; i < 4;   i)
    for(int j = 0; j < 13;   j)
        printf("s\n", deck[i][j]);
}

void shuffleDeck(){

int shuffler[52];
for(int i = 0; i < 52;   i) shuffler[i] = i;

for(int i = 0; i < 52;   i){

    int ind = i (rand()%(52-i));

    int deckI = ind/13;
    int deckJ = ind/13;

    swap(deck[i/13][i], deck[deckI][deckJ]);
}
}

CodePudding user response:

Here we go! So I have added macros to have a more readable code, and also wrote the function create_card_name Here is what is does: it allocates memory for the full name of your card and creates it:

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


#define DECK_SIZE 52
#define SUIT_SIZE 4
#define FACE_SIZE 13


char *suit[SUIT_SIZE] = {"Hearts", "Diamonds", "Clubs", "Spades"};
char *face[FACE_SIZE] = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
                  "Ten", "Jack", "Queen", "King"};

char *deck[SUIT_SIZE][FACE_SIZE];

char * card_name_create(char* face, char* suit)
{
    size_t face_len = strlen(face);
    size_t suit_len = strlen(suit);
    size_t of_len = 4;
    char of[5] = " of ";
    // The size id the size of two strings, than the size of " of " and the '\0'
    char * full_name = malloc(sizeof(char)*(face_len suit_len of_len 1));

    for (size_t i = 0; i < face_len; i  )
    {
        full_name[i] = face[i];
    }
    for (size_t i = face_len; i < face_len of_len; i  )
    {
        full_name[i] = of[i-face_len];
    }
    for (size_t i = face_len of_len; i < face_len of_len suit_len; i  )
    {
        full_name[i] = suit[i - (face_len of_len) ];
    }
    full_name[face_len of_len suit_len] = '\0';
    return full_name;
    
}

void initialiseDeck()
{
    for (int i = 0; i < SUIT_SIZE; i  )
    {
        for (int j = 0; j < FACE_SIZE; j  )
        {
            char * c = card_name_create(face[j],suit[i]);
            deck[i][j] = c;
        }   
    }
        
}

void display()
{
    for (int i = 0; i < SUIT_SIZE; i  )
    {
        for (int j = 0; j < FACE_SIZE; j  )
        {
            printf("s\n", deck[i][j]);
        }
    }        
}

Also it would be a great thing to try to not use triple pointers, that is the case of your deck. You can implement all your strings with simple pointers and use % to loop through them.

  • Related