c - 删除尾随的 NULL 终止符

标签 c string null-terminated

我有一个用 0 填充的大字符数组。我从套接字读取传入文件并将其内容放入缓冲区中。我无法写入包含所有“\0”的缓冲区,因此我分配了一个具有正确大小的新缓冲区并进行写入。 我使用这种方法来做到这一点:

int i = 0;
while(buf[i] != '\0'){
    i++;
}
char new[i];
while(i){
    new[i] = buf[i];
    i--;
}
new[0] = buf[0];

虽然这种方法有效,但它似乎并不是最聪明或最优雅的方法。从字符数组中删除所有尾随 NULL 字符的最佳方法是什么?

最佳答案

我想更简单的方法是:

size_t len = strlen(buf); // will calculate number of non-0 symbols before first 0
char * newBuf = (char *)malloc(len); // allocate memory for new array, don't forget to free it later
memcpy(newBuf, buf, len); // copy data from old buf to new one

关于c - 删除尾随的 NULL 终止符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26069167/

相关文章:

C 字符串和字符

c++ - NULL 终止 c_str()?

c - C 中字符串如何终止?

c - 数值微分方程求解器算法意外出现段错误

c - 在 Xcode 中使用 strcpy 的小例子的问题

c - 如何使 putenv 成为可重入函数?

c - 为什么多个 fgets 语句会覆盖字符数组?

c++ - 拾色轮

arrays - 将 string.Split (',' ) 转换为 int 数组

python - 在列表中查找重复子串