簡體   English   中英

從 C 中的 const char 指針數組打印的垃圾字符串

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

我正在嘗試從 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

在此處輸入圖像描述

似乎有 memory 訪問問題,但我不知道如何解決它。

注意:假設卡片已經隨機發給每個玩家,盡管我可能錯過了一些重要的部分。 所以對於完整的代碼,請看我的 github 這里:

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

您的代碼中的這一行,

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

將不足量的 arguments 傳遞給printf() 由於您的調用中有三個'%' ,因此printf()需要另外三個 arguments,而不是兩個。 但是,由於printf()是作為可變參數 function 實現的,因此它不知道您實際傳遞給它的 arguments 有多少,因此它設法訪問了一些 memory 將占用的位置,從而導致您的第三個參數出現錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM