简体   繁体   English

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

[英]garbage strings printed from a const char pointer array in C

I'm trying to print out slected strings from a const char pointer array but the text displayed is absolutely garbage.我正在尝试从 const char 指针数组中打印出选定的字符串,但显示的文本绝对是垃圾。 I am not sure what went wrong.我不确定出了什么问题。 I condensed the code down for easy read below:为了便于阅读,我将代码压缩如下:

#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]);
    }
}

I changed the printf() part and it still produced the same problem.我改变了 printf() 部分,它仍然产生了同样的问题。

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

在此处输入图像描述

Seems like there is memory access problem but I am not sure how to fix it.似乎有 memory 访问问题,但我不知道如何解决它。

Note: Assuming the cards have already been dealt randomly to each player, although I might have missed some important part.注意:假设卡片已经随机发给每个玩家,尽管我可能错过了一些重要的部分。 So for the full code, please look at my github here:所以对于完整的代码,请看我的 github 这里:

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

This line in your code,您的代码中的这一行,

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

is passing insufficient amount of arguments to printf() .将不足量的 arguments 传递给printf() As there are three '%' in your call, printf() expects another three arguments, not two.由于您的调用中有三个'%' ,因此printf()需要另外三个 arguments,而不是两个。 However, since printf() is implemented as a variadic function, it had no idea how many arguments you actually passed to it, so it managed to access some memory where your non-existent third argument would have occupied, causing the error.但是,由于printf()是作为可变参数 function 实现的,因此它不知道您实际传递给它的 arguments 有多少,因此它设法访问了一些 memory 将占用的位置,从而导致您的第三个参数出现错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM