为什么它会给出错误"分段错误"?

Nar*_*esh -4 c segmentation-fault char-pointer

我想在不同的内存位置输入两个字符串,但在第一次输入后,它显示错误"分段错误(核心转储").我没有弄清楚这段代码有什么问题.

#include <stdio.h>
#include<iostream>
using namespace std;

int main()
{
    char *str;
    int i;
    scanf("%s",str+0);
    scanf("%s",str+1);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,当我只接受一个输入时它工作正常.

#include <stdio.h>
#include<iostream>
using namespace std;

int main()
{
    char *str;
    int i;
    scanf("%s",str+0);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么?

Aru*_*A S 6

因为str在使用它之前没有分配任何内存scanf().

你需要分配一些内存 malloc()

当您尝试访问不安全的内存时,您的代码都会显示未定义的行为.