我正在编写这个函数,它将 n 个字符从 s2 复制到 s1 中。如果 s2 的长度小于 n,则其余 n 个字符将由空字符组成。
main()
{
char sourceStr[10];
char destStr[80];
int myInt;
printf("Enter a string: ");
gets(sourceStr);
printf("Enter the number of characters: ");
scanf("%d", &myInt);
printf("Returned string: %s ", copyastring(destStr, sourceStr, myInt));
return 0;
}
char *copyastring(char * s1, char * s2, int n)
{
int a = n;
for( n ; n > 0 ; n--)
{
// if end of s2 is reached, the rest of s1 becomes null
if(*s2 == '\0')
{
while(n > 0)
{
*s1 = '\0';
s1++;
n--;
}
break;
}
//if-not, copy current s2 value into s1
//increment both pointers
else
{
*s1 = *s2;
s2++;
s1++;
}
}
// Just incase s2 is longer than n, append a null character
s1++;
*s1 = '\0';
s1--;
//Reset s1's pointer back to front of s1
s1 = s1 - a;
return s1;
}
运行此代码并打印出函数返回的字符串后,我意识到所有空字符都被打印为垃圾字符(不可读)。为什么呢?空字符不会终止字符串吗?
提前致谢