我有一个程序从键盘读取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 ) {
;
}
}
答案 0 :(得分:0)
scanf("%79s%79s", string1, string2);
这解决了我的问题。或者可以使用:
scanf_s("%79s %79s", string1,80, string2, 80);
答案 1 :(得分:0)
For&#34;这个函数做了什么?&#34;,答案是,它将两个字符串组合成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
;
}
}