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

C语言字符指针指向值打印失败问题求助

解决C语言字符指针无法打印内容的问题

嘿,我一眼就看出你碰到的问题了!咱们来捋清楚到底怎么回事:

问题根源

你用scanf("%d%c", &num, &ch);的时候,输入数字后按下的换行符被%c直接读取了!

  • %d只会读取连续的数字字符,当你输入完数字按回车,这个回车对应的\n(换行符)会留在输入缓冲区里。
  • 而%c不会跳过空白字符(不像%d会自动跳过空格、换行这些),它会直接把缓冲区里的\n读进ch变量中。
  • 当你打印*ch_ptr的时候,其实是在打印换行符,看起来就是空白,而且程序没有语法错误,所以不会报错。

几种解决方案

方案1:在%c前加空格(最简单稳妥)

在%c前面加一个空格,让scanf自动跳过所有空白字符(包括换行、空格、制表符),这样就能正确读取你输入的字符了:

#include<stdio.h>
int main() { // 标准C推荐用int main(),而非void main()
    int num, *num_ptr;
    char ch, *ch_ptr;
    printf("Enter a number and a single character : ");
    scanf("%d %c", &num, &ch); // 这里%c前面加了空格
    num_ptr = &num;
    ch_ptr = &ch;
    printf("value of the content at num_ptr = %d\n", *num_ptr);
    printf("value of the content at ch_ptr = %c\n", *ch_ptr);
    return 0; // 标准C要求main返回int值
}

方案2:手动清空输入缓冲区

如果不想修改scanf的格式串,可以调整读取逻辑,先读数字,再吃掉缓冲区里的换行符,最后读字符:

#include<stdio.h>
int main() {
    int num, *num_ptr;
    char ch, *ch_ptr;
    printf("Enter a number and a single character : ");
    scanf("%d", &num);
    getchar(); // 吃掉输入数字后留下的换行符
    scanf("%c", &ch);
    num_ptr = &num;
    ch_ptr = &ch;
    printf("value of the content at num_ptr = %d\n", *num_ptr);
    printf("value of the content at ch_ptr = %c\n", *ch_ptr);
    return 0;
}

不过这个方法灵活性稍差,如果用户输入数字后加了多个空格再输入字符,getchar()只能处理一个字符,可能会出问题。

方案3:用fgets+sscanf更安全

如果想从根源避免这类输入缓冲区的问题,推荐用fgets读取整行输入,再用sscanf解析,能避开很多输入相关的坑:

#include<stdio.h>
int main() {
    int num;
    char ch, input[100];
    int *num_ptr = &num;
    char *ch_ptr = &ch;
    
    printf("Enter a number and a single character : ");
    fgets(input, sizeof(input), stdin); // 读取整行输入
    sscanf(input, "%d%c", &num, &ch); // 解析输入内容
    
    printf("value of the content at num_ptr = %d\n", *num_ptr);
    printf("value of the content at ch_ptr = %c\n", *ch_ptr);
    return 0;
}

额外小提示

void main()并不是标准C的写法,C标准规定main函数的返回类型应该是int,并且最后要返回0(表示程序正常结束),虽然有些编译器支持void main(),但为了代码的可移植性,建议改成int main()并返回0。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 12:32:32