【问题标题】:Program crashes by read two strings from keyboard从键盘读取两个字符串导致程序崩溃
【发布时间】:2014-03-30 00:48:18
【问题描述】:

我有一个程序从键盘读取 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 ) {
        ;
    }
}

【问题讨论】:

  • 我认为你需要在 %79s 之间留一个空格
  • 我也做了同样的事情,但还是崩溃了
  • 神秘函数 concat 是两个字符串。
  • @David 该函数不会导致崩溃
  • 我知道,但是在你的代码中你问“这个函数是做什么的?”

标签: c pointers scanf


【解决方案1】:
scanf("%79s%79s", string1, string2);

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

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

【讨论】:

  • Visual Studio 需要使用 scanf_s 而不是 scanf
  • 不,如果您禁用安全开发生命周期检查,它不需要任何东西。即取消选中向导中的字段。
【解决方案2】:

对于“这个函数是做什么的?”,答案是,它将两个字符串组合成string1,而不携带溢出。

void mystery1(char *str1, char *str2) {
    while(*str1 != '\0') { // Is end of string check
        ++str1; // Move pointer position to next character.
    }

        // str1 now points to the first null character of the array.

    for(; *str1 = *str2; ++str1, ++str2) {
        // Sets the current str1 position to equal str2
        // str1 is incremented along with str2, but str1 is starting at the first null character
        ;
    }
}

【讨论】:

  • 请输入退出条件,例如 *s2=='/0'
  • 如果离开退出条件怎么办?我没有发现任何问题
猜你喜欢
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
相关资源
最近更新 更多