c - 从 C 中的 const char 指针数组打印的垃圾字符串
问题描述
我正在尝试从 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:
解决方案
您的代码中的这一行,
printf("[%5s : %-8s%c", suit[s], face[f]);
传递的参数数量不足printf()
。'%'
由于您的通话中有三个,因此printf()
需要另外三个参数,而不是两个。但是,由于printf()
是作为可变参数函数实现的,它不知道您实际传递给它的参数有多少,因此它设法访问了一些您不存在的第三个参数将占用的内存,从而导致错误。
推荐阅读
- javascript - 使用单选按钮组合显示 HTML 元素的逻辑
- android - 启动活动时膨胀类 android.support.v7.widget.RecyclerView 时出错
- r - r闪亮将元素动态添加到反应值
- c++ - 如何阻止着色器扭曲纹理
- android - 无法滚动回收站视图
- android - 广告有时会显示但有时不会
- kubernetes - 使用 configmap 中 json 文件中的特定键作为环境变量
- pyspark - 胶水作业无限期地运行而没有完成代码执行
- arangodb - 如何在启动时创建一个新的测试数据库
- android - 如何强制软键盘不在edittext下隐藏textview/counter?