我最近接受采访并要求写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';
}
你能告诉我这里有什么问题吗?更专业的做法是什么?
最佳答案
两个可能的点
首先,您被告知输入和输出指向有效字符串,因此可以说不需要进行有效性测试。如果需要它,你应该大声失败。更好的做法是:
void mystrcat(char *s1, char *s2, char *s3)
{
ASSERT( s1 );
ASSERT( s2 );
ASSERT( s3 );
....
然后您基本上可以重用 strcat/strcpy:
void mystrcat(char *s1, char *s2, char *s3)
{
strcpy( s3, s1 );
strcat( s3, s2 );
}
如果我面试你的目的不是初级职位,我希望你向我指出指定的 mystrcat 接口(interface)设计得非常好,并提供了你将如何改进它的详细信息。
关于c - 我的串联函数 mystrcat(char*, char*, char*) 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/895419/