-4

我想在不同的内存位置输入两个字符串,但在第一次输入后显示错误“分段错误(核心转储”)。我不明白这段代码有什么问题。

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

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

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

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

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

    return 0;
}

为什么?

4

1 回答 1

6

因为strscanf().

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

当您尝试访问不安全的内存时,您的两个代码都表现出未定义的行为。

于 2015-05-01T10:04:51.747 回答