我有一个用 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/