C语言数组实现栈代码报错修复请求:类型声明与数组下标问题
C语言数组栈实现的编译错误修复
错误原因拆解
1. 「expected declaration specifiers or '...' before 'Stack'」错误
你的头文件里结构体定义写法有误:
struct StackNode{ int data[MAX_SIZE]; struct StackNode *top; } Stack;
这里的Stack是一个具体的struct StackNode变量,不是类型别名。后续函数参数里写Stack *stack,相当于拿变量名当类型使用,编译器无法识别,因此报错。
2. 「array subscript is not an integer」错误
结构体里的top被定义成了struct StackNode *指针类型,但栈的top应该是整数类型——用来标记数组中栈顶元素的下标。用指针作为数组下标,编译器会提示下标不是整数,从而报错。
修复后的完整代码
stackArray.h
#ifndef STACKARRAY_H #define STACKARRAY_H #define MAX_SIZE 10 // 用typedef把struct StackNode定义为别名Stack,简化后续类型使用 typedef struct StackNode { int data[MAX_SIZE]; int top; // 改为int类型,用于记录数组下标 } Stack; void initialize(Stack *stack); int isFull(Stack *stack); int isEmpty(Stack *stack); void push(Stack *stack, int value); int pop(Stack *stack); int peek(Stack *stack); #endif
补充:头文件保护宏改成大写
STACKARRAY_H是C语言通用惯例,避免和变量名冲突。
methods.c
#include "stackArray.h" #include <stdio.h> void initialize(Stack *stack) { stack->top = -1; } int isFull(Stack *stack) { return stack->top == MAX_SIZE - 1; } int isEmpty(Stack *stack) { return stack->top == -1; } void push(Stack *stack, int value) { if (isFull(stack)) { printf("Stack Overflow: Cannot push element %d\n", value); return; } stack->data[++stack->top] = value; printf("Pushed %d onto the stack\n", value); } int pop(Stack *stack) { if (isEmpty(stack)) { printf("Stack Underflow: Cannot pop from an empty stack\n"); return -1; // 返回哨兵值表示栈下溢 } return stack->data[stack->top--]; } int peek(Stack *stack) { if (isEmpty(stack)) { printf("Stack is empty\n"); return -1; // 返回哨兵值表示栈为空 } return stack->data[stack->top]; }
main.c
#include <stdio.h> #include <stdlib.h> #include "stackArray.h" int main() { Stack stack; initialize(&stack); push(&stack, 10); push(&stack, 20); push(&stack, 30); if (!isEmpty(&stack)) { printf("Top element: %d\n", peek(&stack)); } else { printf("Stack is empty\n"); } printf("Popped: %d\n", pop(&stack)); printf("Popped: %d\n", pop(&stack)); if (!isEmpty(&stack)) { printf("Top element: %d\n", peek(&stack)); } else { printf("Stack is empty\n"); } return 0; }
内容的提问来源于stack exchange,提问作者don Maleesha
相关产品推荐
相关产品推荐

