为什么scanf会在读取字符串时崩溃?

Gal*_*tus 0 c string scanf

这只是我编写的一个小程序,用于查找较大的问题.当我用scanf添加行时,一切都会改变.我知道它不安全,我读了关于printf错误的其他线程,这些错误暗示了其他功能.除了cin之外什么都没关系.顺便说一句,我没有选择来自我老师的"消息"的类型定义,所以我无法改变它们.

#include <stdio.h>
#include <string.h>


char message1 [] = "amfdalkfaklmdklfamd.";
char message2 [] = "fnmakajkkjlkjs.";
char initializer [] = ".";
char* com;
char* word;
int main()
{   
    com = initializer;
    int i = 1;
    while (i !=4)
    {   
        printf ("%s \n", com);
        scanf("%s",word);
        i++;
    };  
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

问题:在一次迭代后程序退出,没有打印任何内容.

das*_*ght 6

scanf将崩溃的原因是缓冲区未初始化:word尚未分配值,因此它指向无处.

您可以通过为缓冲区分配一些内存并限制scanf为一定数量的字符来修复它,如下所示:

char word[20];
...
scanf("%19s", word);
Run Code Online (Sandbox Code Playgroud)

注意,之间的数量%s其表示字符串中的字符的最大数目,是少1比实际缓冲器的长度.这是因为null终止符,这是C字符串所必需的.