我正在寫這個函數,它將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;
}
運行該代碼,並打印出由該函數返回字符串後,我發現所有的空字符打印爲亂碼(不可讀)。爲什麼?不是空字符終止字符串?
在此先感謝
如何打印函數返回的字符串? – 2013-02-11 12:51:14
字符串是如何聲明的以及如何調用函數? – cnicutar 2013-02-11 12:51:37
你確定's1'被分配到足夠大的尺寸嗎?與這個問題無關,但是你認爲''for'語句中有什麼''n'' – 2013-02-11 12:56:11