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

C语言中void函数打印输入时输出null问题求解

问题分析与解决

你的代码存在两个关键问题:

  • 数组越界访问:调用read函数时传的input[2048]是超出数组范围的元素。input数组大小为2048,有效下标范围是0到2047,访问input[2048]属于未定义行为,获取到的是随机内存值。
  • 参数类型不匹配:第一个版本的read函数参数是单个char,但printf("%s")要求传入字符串指针(char*),类型不匹配会触发未定义行为;即使你把函数参数改为char*,但调用时传入的还是单个char值,这个值会被当作内存地址,而该地址几乎肯定是无效的,所以输出(null)。

修正后的代码

#include <stdio.h>

static char input[2048];

void read(char *input){
    printf("%s", input);
}

int main(){
    fputs("test> ", stdout);
    
    fgets(input, 2048, stdin);
    
    read(input); // 直接传入数组名,数组名会隐式转换为指向首元素的指针
}

额外优化(可选)

fgets会将输入末尾的换行符也读入数组中,如果不需要这个换行符,可以添加代码去除:

#include <stdio.h>
#include <string.h> // 需要包含string.h头文件

static char input[2048];

void read(char *input){
    printf("%s", input);
}

int main(){
    fputs("test> ", stdout);
    
    fgets(input, 2048, stdin);
    input[strcspn(input, "\n")] = '\0'; // 替换换行符为字符串结束符
    
    read(input);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:25:27