未对齐地址0x中的成员访问属于struct ...类型,需要4字节对齐

时间:2018-10-10 12:14:21

标签: c

对于纸牌游戏,我具有这两种结构和功能(不幸的是,typedef指针被强制执行,我无法更改它们)

typedef struct cardStack {
    struct cardStack *next;
    Card card;
} *CardStack;

typedef struct _game {
    CardStack discardPile;
    CardStack drawPile; 
    CardStack playerHand[4];
    int currentPlayer;
    int previousTurnPlayer;
    int currentTurn;
    int currentTurnMoves;
    int numTurns;
    int topDiscardTurnNumber;
} *Game;

static void addToStack(Card card, CardStack head){  
    CardStack newCard = malloc(sizeof *newCard);
    newCard->card = card;
    newCard->next = NULL;

    if (head->next == NULL) {
        head = newCard;
    } else {    
        CardStack current = head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newCard;
    }
}

我初始化我的4个玩家的手,将头节点的下一个成员设置为NULL。

game->playerHand[0] = malloc(sizeof(CardStack));
game->playerHand[0]->next = NULL;
printf("%p\n", game->playerHand[0]->next);
game->playerHand[1] = malloc(sizeof(CardStack));
game->playerHand[1]->next = NULL;
game->playerHand[2] = malloc(sizeof(CardStack));
game->playerHand[2]->next = NULL;
game->playerHand[3] = malloc(sizeof(CardStack));
game->playerHand[3]->next = NULL;

printf给我(无)

然后我想向每位玩家分发7张牌(添加到他们的手动链接列表的末尾)

for (int i = 0; i < 7; i++) {
    for (int j = 0; j < NUM_PLAYERS; j++) {
        Card card = newCard(values[4 * i + j], colors[4 * i + j], suits[4 * i + j]);
        addToStack(card, game->playerHand[j]);
    }
}

但是我在函数中遇到此错误:

runtime error: member access within misaligned address 0xbebebebe for type 'struct cardStack', which requires 4 byte alignment
0xbebebebe: note: pointer points here
<memory cannot be printed>

Execution stopped here in addToStack(card=0xf5500ef0, head=0xf5500f10) in Game.c at line 156:

        } else {
                CardStack current = head;
-->             while (current->next != NULL) {
                        current = current->next;
                }

我不知道为什么我可以完美地打印NULL指针,但是当我将其传递给函数时,会出现此错误。任何帮助将不胜感激。

0 个答案:

没有答案