C函数返回字符数组的问题

时间:2013-11-12 23:10:22

标签: c arrays function debugging character

这是我正在处理的作业的头文件中的一个功能。

#ifndef CARDGAMES_H
#define CARDGAMES_H

#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdio.h>

typedef struct {
    char suit;
    char label;
    int value;
} card ;

//function prototypes (removed the majority of them, this is just a segment of header file)

void addToDeck(card deck[], card toAdd, int * deckLength);
void printDeck(card deck[], int deckLength);

card removeCard(card deck[], int * deckLength, int index);


*/
card removeCard(card deck[], int * deckLength, int index){
        card removed = deck[index];
        int x = *deckLength;
        deck[index] = deck[x];
        deck[x] = removed;
        x=x-1;
        *deckLength = x;
        return removed;

以下是我正在测试此功能的驱动程序部分...我的问题出现了。

printf("\tThe deck after adding the ten of hearts: \n");
    printDeck(deck, ncards);

        printf("Testing removeCard.\n");

    removeCard(deck, &ncards, 0);
    printf("\tThe deck after removing the first card: ");
    printDeck(deck, ncards);

运行编译程序后,下面是我的输出:

     The deck after adding the ten of hearts: 
King of hearts
King of spades
King of diamonds
Queen of diamonds
ten of hearts
Testing removeCard.
    The deck after removing the first card: ten �?D
King of spades
King of diamonds
Queen of diamonds

这就像我希望的那样。然而十颗心没有正确打印。它有�?D?谁能解释一下我在哪里出错?

1 个答案:

答案 0 :(得分:0)

在C数组中从0开始,所以

    int x = *deckLength;
    deck[index] = deck[x];

错了。数组的最后一个元素有arraySize - 1索引。

正确的代码应该是

card removeCard(card deck[], int * deckLength, int index){
        card removed = deck[index];
        int indexLast = *deckLength - 1;
        deck[index] = deck[indexLast];
        deck[indexLast] = removed;
        *deckLength -= 1;
        return removed;