gpt4 book ai didi

c - 加入路径时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 01:38:12 25 4
gpt4 key购买 nike

我写这个函数是为了在 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++;。有什么想法吗?

最佳答案

while (tmp1 != NULL) 不正确。
应该是 while (*tmp1 != '\0')
指针本身永远不会变为 NULL。正是它所指向的。

关于c - 加入路径时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10671325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com