我正在尝试解决在我的C编程书中发现的问题。
#include <stdio.h>
char *f (char s[], char t[], char out[]);
int main(void)
{
char s[] = "ISBN-978-8884981431";
char t[] = "ISBN-978-8863720181";
char out[10];
printf ("%s\n", f(s,t,out));
return 0;
}
char *f (char s[], char t[], char out[]) {
int i;
for (i=0; s[i] == t[i]; i++)
out[i] = s[i];
out[i] = '\0';
return &out[0];
}
从代码中可以看出,此代码使用 &out[0] 作为返回值:这是否意味着整个数组被用作返回值?
char *f (char s[], char t[], char out[]);
int main(void)
{
char s[] = "ISBN-978-8884981431";
char t[] = "ISBN-978-8863720181";
char out[10];
printf ("%s\n", f(s,t,out));
return 0;
}
char *f (char s[], char t[], char out[]) {
for (; *(s+=1) == *(t+=1);)
*(out+=1) = *s;
*(out+1) = '\0';
return out;
}
这是我提出的解决方案,但是提出的代码返回"ISBN-978-88",而我的只返回"8"。数组比字符串长度小,为什么提出的代码可以在没有任何类型的溢出的情况下工作呢?感谢您的回应。
*(out+1)='\0';
,你可以在索引1处以NULL终止字符结束字符数组。因此,在打印输出时,你只能看到一个字符。 - Deidreiout
的初始值复制到另一个变量中,并在最后返回该变量。此外,for
循环通常会写成while(*++s == *++t)
。 - Jon