s2からs1にn文字をコピーするこの関数を書いています。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;
}
このコードを実行し、関数によって返された文字列を出力した後、すべてのヌル文字がガベージ文字(読み取り不能)として出力されていることに気付きました。どうしてこんなことに?ヌル文字は文字列を終了しませんか?
前もって感謝します