user2300867 user2300867 - 1 month ago 19
C Question

How to get the value of const char *

New to C and trying to understand pointers and how to work with them. I understand a pointer is a reference to memory location and I think I get the basics and simple examples, but how can I assign the value of a const char pointer to a char?

When I try I get warning;

incompatible pointer to integer conversion initializing 'char' with an expression of type 'const char *' [-Wint-conversion]


I understand the type difference but how do I go about solving it.

Here is the code:

#include <time.h>
#include <stdbool.h>

#define SUITS 4
#define FACES 13
#define CARDS 52
#define HAND_SIZE 5

struct Card {
char suit;
char face;
};

void dealHand(const char *wFace[], struct Card *wHand[]);

int main(void)
{
//initialize deck array
unsigned int deck[SUITS][FACES] = {0};

srand(time(NULL)); // seed random-number generator

//initialize face array
const char *face[FACES] =
{"Ace", "Deuce", "Three", "Four",
"Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Jack", "Queen", "King"};

struct Card *hand[HAND_SIZE];
dealHand(face, hand); //deal the deck

}

//deal cards in deck
void dealHand(const char *wFace[], struct Card *wHand[])
{
unsigned int c = 0;
char f = wFace[2];
struct Card aCard;
aCard.face = f;
wHand[0] = &aCard;
}


I get warning on line:

char f = wFace[2];


Casting it using (const *) doesn't seem to be a solution.

sg7 sg7
Answer

how can I assign the value of a const char pointer to a char?"

You should not do that. You need to print the whole name not just a first character of the name.

You are retrieving the pointer to const string so the code should be like:

const char *f = wFace[2];

Also

struct Card {
   char suit;
   const char *face;
};

and than aCard.face = f; will work.

void dealHand(const char *wFace[], struct Card *wHand[])
{
unsigned int c = 0;
const char *f = wFace[2];
struct Card aCard;
aCard.face = f;
wHand[0] = &aCard;
printf( "%s",f);
}

Will print:

Three