C 程序因从键盘读取两个字符串而崩溃
我有一个程序,从键盘上读取2个字符串,string1将被string2取代。问题是程序在我按下回车键后就崩溃了。大家能解释一下我的程序出了什么问题吗?谢谢大家!C 程序因从键盘读取两个字符串而崩溃,c,pointers,scanf,C,Pointers,Scanf,我有一个程序,从键盘上读取2个字符串,string1将被string2取代。问题是程序在我按下回车键后就崩溃了。大家能解释一下我的程序出了什么问题吗?谢谢大家! #include<stdio.h> #define SIZE 80 void mystery1( char *s1, const char *s2 ); int main( void) { char string1[ SIZE]; char string2[ SIZE ]; puts("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 ) {
;
}
}
#包括
#定义大小80
void mystery1(字符*s1,常量字符*s2);
内部主(空)
{
字符字符串1[大小];
字符字符串2[大小];
puts(“输入两个字符串:”);
scanf_s(“%79s%79s”,string1,string2);//这一行使程序崩溃
神秘1(第1条、第2条);
printf_s(“%s”,string1);
}
//这个函数做什么?
void mystery1(字符*s1,常量字符*s2)
{
而(*s1!='\0'){
++s1;
}
对于(;*s1=*s2;++s1,++s2){
;
}
}
这为我解决了问题。或可使用:
scanf_s("%79s %79s", string1,80, string2, 80);
对于“这个函数做什么?”,答案是,它将两个字符串组合成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
;
}
}
我认为您需要在%79sI之间留一个空格,但仍然会崩溃神秘函数concat的两个字符串。@David该函数不会导致崩溃我知道,但在您的代码中您会问“这个函数做什么?”Visual Studio要求使用scanf_s而不是scanfNo它不需要任何东西,如果禁用安全开发生命周期检查。i、 e.取消选中向导中的字段。请输入一个退出条件,如*s2='/0'如果您离开退出条件怎么办?我看没什么问题
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
;
}
}