简体   繁体   中英

C Program - How to assign values of a char* array to a 2d char* array?

Im trying to initialize a 2d array representing a deck of cards from 2 char pointer arrays called faces and suit representing the faces and suits of cards. I'm getting various errors shown below and cannot work out how to properly add values to my deck as well display my deck. Could anyone point out to me what needs to change in order for my code to work? Thank you.

#include <stdio.h>
#include <string.h>
#include "functions.h"

char **deck[4][13];

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

char** initializeDeck(char** arr)
{
    char addToString[] = " of ";
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 13; j++)
        {
            arr[i][j] =  *faces[j], addToString, *suit[i]
        }
    }
    return arr;
}

void displayDeck(char** arr){
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 13; j++)
        {
            printf("[%s] ", **arr[i][j]);
        }
        printf("\n");
    }
}

errors:

functions.c:35:37: warning: expression result unused [-Wunused-value]
            arr[i][j] =  *faces[j], addToString, *suit[i];
                                    ^~~~~~~~~~~
functions.c:35:50: warning: expression result unused [-Wunused-value]
            arr[i][j] =  *faces[j], addToString, *suit[i];
                                                 ^~~~~~~~
functions.c:46:30: error: indirection requires pointer operand ('int' invalid)
            printf("[%s] ", **arr[i][j]);
  1. arr[i][j] = *faces[j], addToString, *suit[i] is not contcatenating the strings together.

Here you have some code but I do not think that your teacher will belive that is your code

char *myconcat(const char *s1, const char *s2, const char *s3)
{
    size_t len = strlen(s1) + strlen(s2) + strlen(s3);
    char *newstr = malloc(len + 1);
    
    if(newstr)
    {
        strcpy(newstr, s1);
        strcat(newstr, s2);
        strcat(newstr, s3);
    }
    return newstr;
}


char *(*initializeDeck(void))[13]
{
    char *(*cards)[13] = malloc(4 *sizeof(*cards));
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 13; j++)
        {
            cards[i][j] =  myconcat(faces[j], " of ", suit[i]);
        }
    }
    return cards;
}

void displayDeck(char *(*cards)[13]){
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 13; j++)
        {
            printf("[%s] ", cards[i][j]);
        }
        printf("\n");
    }
}

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