c - 从键盘读取两个字符串导致程序崩溃

标签 c pointers scanf

我有一个程序从键盘读取 2 个字符串,string1 将被 string2 替换。问题是我按 Enter 后程序立即崩溃。大家能解释一下我的程序出了什么问题吗?谢谢!

#include<stdio.h>
#define SIZE 80

void mystery1( char *s1, const char *s2 );

int main( void)
{
    char string1[ SIZE];
    char string2[ SIZE ];
    puts("Enter two strings: ");
    scanf_s("%79s%79s",string1,string2); // this line makes program crashed
    mystery1(string1, string2);
    printf_s("%s", string1);
}

// What does this function do?
void mystery1(char *s1, const char *s2 )
{
    while ( *s1 != '\0') {
        ++s1;
    }

    for( ; *s1 = *s2; ++s1, ++s2 ) {
        ;
    }
}

最佳答案

scanf("%79s%79s", string1, string2);

这解决了我的问题。或者可以使用:

scanf_s("%79s %79s", string1,80, string2, 80);

关于c - 从键盘读取两个字符串导致程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22738916/

相关文章:

c - 指针数组的问题

c - scanf() 将换行符保留在缓冲区中

c - 什么是段错误?为什么该程序显示段错误?

c - C 中的多线程问题

c++ - vector 排序和更改数据

c++ - 如何有效地检索数字的第一个十进制数字

c++ - 如何从字符串中查找子字符串?

c - 为什么我收到编译错误 "error: conflicting types for ‘ptr’“以下代码? static int val=33; int *ptr;//=&val; ptr=&val;

复制/分配 char * 指针数据

c - 从 scanf 到结构的输入值