C新手,试图理解指针以及如何使用它们。我理解指针是对内存位置的引用,我想我得到了基础和简单的例子,但是如何将const char指针的值赋给char呢?
当我尝试时,我会收到警告;
incompatible pointer to integer conversion initializing 'char' with an expression of type 'const char *' [-Wint-conversion]
我理解类型差异,但我该如何解决它。
以下是代码:
#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;
}
我在网上收到警告:
char f = wFace[2];
使用(const *)进行转换似乎不是一个解决方案。
答案 0 :(得分:4)
char f = wFace [2];
f
是字符,其范围可能是[-128,127](不是必需的)。
wFace[2]
的值是指向内存地址的指针。
你在这里分配不同的类型,你期望什么?
这是wFace[2]
的价值:
wFace[2] == 0x1000
一些内存地址。
然后看看内存
Memory address: 0x1000 0x1001 0x1002 0x1003
Value stored: H i ! 0
如果你*wFace[2]
它会给你&#39; H&#39;背部;如果你做*(wFace[2]+1)
它会给你&#39;我&#39;回来。
你更可能想要的可能是:
const char *f = wFace[2];
答案 1 :(得分:1)
如何将const char指针的值赋给char?&#34;
你不应该这样做。您需要打印整个名称,而不仅仅是名称的第一个字符。
您正在检索指向const字符串的指针,因此代码应该是:
const char *f = wFace[2];
另外
struct Card {
char suit;
const char *face;
};
而不是
aCard.face = f;
可以使用。
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);
}
将打印:
Three