首页 > 解决方案 > C [Array] 问题中的堆栈实现-“this”必须是可修改的左值

问题描述

我正在研究 C 中堆栈的通用实现,在尝试推送或弹出时,我似乎遇到了上述错误。下面是我的代码:

头文件:

#ifndef STACK_H_
#define STACK_H_

#include <stdbool.h>

typedef struct Stack Stack;

struct Stack {
    void* element;
    int top;
    int capacity;
    int size; 
};


Stack* new_Stack(int max_size);

bool Stack_push(Stack* this, void* element);

void* Stack_pop(Stack* this);

int Stack_size(Stack* this);

bool Stack_isEmpty(Stack* this);

#endif 

C 文件:

#include <stddef.h>
#include "Stack.h"

Stack *new_Stack(int max_size) {
    Stack* stack = malloc(sizeof(Stack)); 
    stack->capacity = max_size; 
    stack->top = -1; 
    stack->size = 0;
    stack->element = calloc(sizeof(void*)*max_size); 
    return stack;
}

bool Stack_push(Stack* this, void* element) {

    if (this->top >= this->capacity-1){
        return false;
    }

    this->element[this->top++] = element;
    return true;
}


void* Stack_pop(Stack* this) {

    if(Stack_isEmpty(this)){
        return NULL;
    }
    else {
        return this->element[this->top--];
    }
}

int Stack_size(Stack* this) {
    return this->size; 
}


bool Stack_isEmpty(Stack* this) {
    if(this->top = -1){
        return true;
    }
    else {
        return false;
    }
}

在 push() 和 pop() 函数中,行“this->element[this->top++] = element;” 和“返回 this->element[this->top--]”,导致错误“必须是可修改的左值”。

标签: carraysgenericsstack

解决方案


推荐阅读