我编写了这个函数来加入 C 中的两条路径;
void *xmalloc(size_t size)
{
void *p = malloc(size);
if (p == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
return p;
}
char *joinpath(char *head, char *tail)
{
size_t headlen = strlen(head);
size_t taillen = strlen(tail);
char *tmp1, *tmp2;
char *fullpath = xmalloc(sizeof(char) * (headlen + taillen + 2));
tmp1 = head;
tmp2 = fullpath;
while (tmp1 != NULL)
*tmp2++ = *tmp1++;
*tmp2++ = '/';
tmp1 = tail;
while (tmp1 != NULL);
*tmp2++ = *tmp1++;
return fullpath;
}
但是我在第一个 while 循环中遇到了段错误,在*tmp2++ = *tmp1++;
. 有任何想法吗?