You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言实现Stack时printf格式符不匹配引发段错误求助

问题分析与修复方案

错误原因

你遇到的format '%s' expects argument of type 'char *', but argument 2 has type 'int'错误,核心是格式符与变量类型不匹配:

  • printf("%s", item)中,%s用于打印字符串(需传入char*类型指针),但item是单个char类型变量。char会被隐式转换为int,和%s要求的指针类型不匹配,直接引发内存访问错误(段错误)。

修复方法

将打印语句的格式符改为%c(用于输出单个字符)即可:

printf("%c", item);

额外优化建议

  • new是C++关键字,虽C语言允许使用,但为了代码兼容性和可读性,建议把push函数的第三个参数名改为new_char;
  • 原push函数的判断条件*top < STACK_SIZE存在数组越界风险:栈数组下标范围是0到STACK_SIZE-1,当*top等于STACK_SIZE-1时栈已存满,再执行(*top)++会导致访问stack[STACK_SIZE](超出数组边界),因此判断条件应改为*top < STACK_SIZE - 1;
  • 提示语句末尾建议添加换行符,让输出更规范。

修复后的完整代码

#include <stdio.h>
#define STACK_SIZE 20

void push(char stack[], int *top, char new_char){
    if(*top < STACK_SIZE - 1){
        (*top)++;
        stack[*top] = new_char;
    }
    else
        printf("Stack is full!\n");
}

char pop(char stack[], int *top){
    char item;
    if(*top >= 0){
        item = stack[*top];
        (*top)--;
    }else{
        printf("stack is empty\n");
        item = ' ';
    }
    return item;
}

int main(){
    char s[STACK_SIZE];
    int s_top = -1;
    push(s, &s_top, 'C');
    push(s, &s_top, 'A');
    push(s, &s_top, 'H');
    char item = pop(s, &s_top);
    printf("%c", item);
    return 0;
}

内容的提问来源于stack exchange,提问作者mohsentajdeh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 08:05:26