我很抱歉,如果这是入门级别,但我尝试实现 strcpy strncat()
的库函数,如下所示:
#include <stdio.h>
void strncat (char *s, char *t, int n) {
// malloc to extend size of s
s = (char*)malloc (strlen(t) + 1);
// add t to the end of s for at most n characters
while (*s != '\0') // move pointer
s++;
int count = 0;
while (++count <= n)
*s++ = *t++;
*(++s) = '\0';
}
int main () {
char *t = " Bluish";
char *s = "Red and";
// before concat
printf ("Before concat: %s\n", s);
strncat(s, t, 4);
// after concat
printf ("After concat: %s\n", s);
return 0;
}
它编译并运行良好......只是它根本不连接!
非常感谢任何反馈......谢谢!
答案 0 :(得分:3)
看起来你用malloc重新定义了s指针,因为你已经完成了它,它并没有指向你的第一个连接字符串。
首先,函数返回类型应为char *
char* strncat (char *s, char *t, int n)
之后,我认为你应该创建本地字符指针。
char* localString;
使用malloc为此指针分配空间
localString = malloc (n + strlen(s) + 1);
你不需要在这里进行类型转换,cuz malloc自己动手
实际上,你应该在这里使用你的尺寸参数(n),而不是strlen(t)
并在使用此指针执行所有连接操作后返回
return localString