gpt4 book ai didi

无法弄清楚为什么这个修剪功能不能正常工作

转载 作者:太空狗 更新时间:2023-10-29 15:59:31 26 4
gpt4 key购买 nike

============================================= ================================

void trim(const char * orig, char * dest)
{
size_t front = 0;
size_t end = sizeof(orig) - 1;
size_t counter = 0;
char * tmp = null;

if (sizeof(orig) > 0)
{
memset(dest, '\0', sizeof(dest));

/* Find the first non-space character */
while (isspace(orig[front]))
{
front++;
}
/* Find the last non-space character */
while (isspace(orig[end]))
{
end--;
}

tmp = strndup(orig + front, end - front + 1);
strncpy(dest, tmp, sizeof(dest) - 1);
free(tmp); //strndup automatically malloc space
}
}

============================================= ================================

我有一个字符串:

' ABCDEF/G01 '

上面的函数应该删除空格并返回给我:

'ABCDEF/G01'

相反,我得到的是:

'ABCDEF/'

有什么想法吗?

注意:引号只是为了告诉您原始字符串中存在空格。

最佳答案

strncpy 是错误的。 sizeof(dest) 不是您想要的(它是您机器上指针的大小)。您可能需要:end - front。相反,请尝试:

memcpy(dest, front + start, end - front);
dest[end] = 0;

关于无法弄清楚为什么这个修剪功能不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8095858/

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