C语言字符串复制函数错误分析及修正
#include<stdio.h>
void my_strcpy(char s1[], char s2[]) { int i = 0; while(s2[i] != '\0') { char temp=s1[i]; s1[i]=s2[i]; s2[i]=temp; i++; } }
int main() { int i; char s1[100], s2[100]; scanf('%s',s2); my_strcpy(s1,s2); printf('%s',s1); return 0; }
There are several errors in the code:
- Missing semicolon after declaring s1 array in main function.
- The 'i' variable in 'my_strcpy' function is not initialized.
- The 'my_strcpy' function should use a loop to iterate over the characters in 's1' and 's2' arrays.
- The 'scanf' function should read input into 's2' array, not 's1'.
Here's the corrected code:
#include<stdio.h>
void my_strcpy(char s1[], char s2[]) { int i = 0; while(s2[i] != '\0') { char temp=s1[i]; s1[i]=s2[i]; s2[i]=temp; i++; } }
int main() { int i; char s1[100], s2[100]; scanf('%s',s2); my_strcpy(s1,s2); printf('%s',s1); return 0; }
原文地址: https://www.cveoy.top/t/topic/mNyw 著作权归作者所有。请勿转载和采集!