我最近接受采访,要求写mystrcat(*s1, *s2, *s3)在那里s1,并s2在源字符串和串联的结果给出s3.我被告知,不要担心内存分配s3和假设s1,s2并且不是空/无效字符串.所以我写了下面的蹩脚(粗)程序.我被告知有问题s3或出现问题s3.你能告诉它它是什么/可能是什么?
void mystrcat(char *s1, char *s2, char *s3)
{
if (! (s1 || s2 || s3)) return; // one/more pointers are invalid
// copy string s1 into s3
while(*s1) {
*s3 = *s1;
s1++;
s3++;
}
// concatenate string s2 into s3
while(*s2) {
*s3 = *s2;
s2++;
s3++;
}
*s3 = '\0';
}
Run Code Online (Sandbox Code Playgroud)
你能告诉我这里有什么问题吗?做什么会更专业呢?
if (! (s1 || s2 || s3) return; // one/more pointers are invalid
Run Code Online (Sandbox Code Playgroud)
应该
if ((!s1) || (!s2) || (!s3)) return;
Run Code Online (Sandbox Code Playgroud)
小智 7
两个可能的点
首先,您被告知输入和输出指向有效字符串,因此可以说不需要测试有效性.如果需要,你应该吵闹失败.更好的是:
void mystrcat(char *s1, char *s2, char *s3)
{
ASSERT( s1 );
ASSERT( s2 );
ASSERT( s3 );
....
Run Code Online (Sandbox Code Playgroud)
然后你基本上写了strcat/strcpy,你可以重用它们:
void mystrcat(char *s1, char *s2, char *s3)
{
strcpy( s3, s1 );
strcat( s3, s2 );
}
Run Code Online (Sandbox Code Playgroud)
如果我正在采访你以外的其他任何事情,我会特别指出你指出我指定的mystrcat界面是非常精心设计的,并提供了如何改进它的细节.
这是我的评论
const char*因为您无意修改它们.我希望你在面试中问我或自己回答的问题