【发布时间】:2020-08-14 02:51:16
【问题描述】:
我正在尝试从 const char 指针数组中打印出选定的字符串,但显示的文本绝对是垃圾。我不确定出了什么问题。为了便于阅读,我将代码压缩如下:
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define HAND_CARDS 5 /* maximum number of cards any particular Hand */
typedef struct card {
int suit;
int face;
} Card;
typedef struct hand {
struct card pHand[5];
int hQuality;
} Hand;
void print_pHand(struct hand player, const char* suit[], const char* face[]);
int main(void)
{
/* initialize memory arrays of suit and face, to be referenced through out the game */
const char *suit[4] = {"Hearts", "Diamonds", "Clubs", "Spades"};
const char *face[13] = {"Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Jack", "Queen", "King"};
int deck[4][13] = { 0 };
Hand pHuman = { 0 };
print_pHand(pHuman, suit, face);
return 0;
}
void print_pHand(struct hand player, const char* suit[], const char* face[])
{
int f = 0, s = 0, i = 0;
for (i = 0; i < HAND_CARDS; ++i) {
s = player.pHand[i].suit;
f = player.pHand[i].face;
printf("[%s : %s]\t", suit[s], face[f]);
}
}
我更改了 printf() 部分,但仍然产生同样的问题。
Unhandled exception at 0x79B81F4C (ucrtbased.dll) in PA7.exe:
0xC0000005: Access violation reading location 0xF485A8D3. occurred
似乎存在内存访问问题,但我不知道如何解决。
注意:假设卡片已经随机发给每个玩家,尽管我可能错过了一些重要的部分。所以完整代码请看我的github:
【问题讨论】:
-
@karln-createt pHuman 初始化为零。
-
"[%5s : %-8s%c"需要 3 个参数而不是 2 个 -
@Vlad 来自莫斯科,但结构的内部参数是整数。所以初始化为零与否无关紧要?另外,我使用索引来定位数组的块,从中存储字符串。
-
@karln-create 我的意思是这个电话没有多大意义。同样在 printf 调用中,您使用的参数数量不正确。
-
这是最小完整可验证示例发挥作用的地方。削减它,但验证削减的版本是否表现出有问题的行为。如果没有,那应该会提示您问题实际出在哪里。
标签: c arrays pointers char constants