从C中的const char指针数组打印的垃圾字符串

问题描述 投票:0回答:1

我正在尝试从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("[%5s : %-8s%c", suit[s], face[f]);
    }
}

我更改了printf()部分,但仍然产生相同的问题。

Unhandled exception at 0x79B81F4C (ucrtbased.dll) in PA7.exe:
0xC0000005: Access violation reading location 0xF485A8D3. occurred

enter image description here

似乎有内存访问问题,但是我不确定如何解决。

注意:假设已经随机发给每个玩家纸牌,尽管我可能错过了一些重要的部分。因此,有关完整代码,请在此处查看我的github:

https://github.com/karln-create/PA7-5CDPoker

c arrays pointers char const
1个回答
0
投票

您代码中的这一行,

printf("[%5s : %-8s%c", suit[s], face[f]);

没有将足够数量的参数传递给printf()。由于您的呼叫中有三个'%',因此printf()期望另外三个参数,而不是两个。但是,由于printf()是作为可变函数实现的,它不知道您实际传递给它多少个参数,因此它设法访问了一些内存,这些内存将占用您不存在的第三个参数,从而导致错误。

© www.soinside.com 2019 - 2024. All rights reserved.