函数返回字符数组时的C问题
这是我正在处理的作业头文件中的一个函数函数返回字符数组时的C问题,c,arrays,function,debugging,character,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
#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;
下面是我运行编译程序后的输出:
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
这正是我所希望的。然而,十颗红心没有正确印刷。它有�?你在里面干什么?有人能解释一下我哪里出错了吗?在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;
更改int x=*deckLength;到int x=*deckLength-1;和*deckLength=x;至*deckLength=*deckLength-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;