C中的分段错误将字符串赋值给char

kar*_*k A 0 c

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char a="9jhjhi";
    printf("%s",a);
}
Run Code Online (Sandbox Code Playgroud)

为什么这会引发分段错误?屏幕背后会发生什么?

wkl*_*wkl 5

你需要使用char *a = "...".

printf传递时%s将通过字符串查找0/ NULLbyte.在你的情况下,你没有分配字符串文字a,实际上你的编译器应该抛出一个警告,你试图char从指针初始化a .

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char *a="9jhjhi";
    printf("%s",a);
}
Run Code Online (Sandbox Code Playgroud)