灰尘驾车 2022-09-07 22:12 采纳率: 71.4%
浏览 35
已结题

为什么printf函数不工作

img

img


在线编译这个程序,printf函数正常工作,但是在vs里输入了字符串就没反应了

  • 写回答

3条回答 默认 最新

  • _GX_ 2022-09-07 23:04
    关注

    因为scanf_s()为了防止内存越界,当指定缓存没有足够空间存放输入数据时,scanf_s()直接返回,输入数据没有拷贝到指定缓存。

    在你的程序里s数组大小是6,最多只能存储5个字符和'\0',而你却输入了6个字符,s没有足够的空间来存储你输入的字符串,因此scanf_s()直接返回,s数组里的内存没有被修改。

    scanf()没有这个问题,因为scanf()不检查数组边界,也因此不安全,容易内存溢出越界。

    https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/scanf-s-scanf-s-l-wscanf-s-wscanf-s-l?view=msvc-170

    The buffer size includes the terminal null. You can use a width specification field to ensure the token that's read in fits into the buffer. When a token is too large to fit, nothing is written to the buffer unless there's a width specification.

    #include <stdio.h>
    
    int main()
    {
        char s[6] = "";
        if (scanf_s("%s", s, 6) != 1)
        {
            perror("failed to read a string with max 5 chars");
            return 1;
        }
        printf("%s\n", s);
        return 0;
    }
    
    C:> cl main.cpp
    C:> main.exe
    123456
    failed to read a string with max 5 chars: Not enough space
    C:> main.exe
    12345
    12345
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 9月22日
  • 已采纳回答 9月14日
  • 创建了问题 9月7日

悬赏问题

  • ¥20 python忆阻器数字识别
  • ¥15 无法输出helloworld
  • ¥15 高通uboot 打印ubi init err 22
  • ¥20 PDF元数据中的XMP媒体管理属性
  • ¥15 R语言中lasso回归报错
  • ¥15 网站突然不能访问了,上午还好好的
  • ¥15 有没有dl可以帮弄”我去图书馆”秒选道具和积分
  • ¥15 semrush,SEO,内嵌网站,api
  • ¥15 Stata:为什么reghdfe后的因变量没有被发现识别啊
  • ¥15 振荡电路,ADS仿真