我有一个指针,指向在运行时动态填充的数组。在收集和存储数组之后,我希望数组的所有剩余缓冲区位置都填充空空间。我怎么能这么做?
根据一些评论:
以下是我所拥有的:
char buf[50];
char *ptr = buf;
strncpy(ptr, info.a, strlen(info.a));
ptr += strlen(info.a);
strncpy(ptr, info.b, strlen(info.b));
ptr += strlen(info.b);
strncpy(ptr, info.c, strlen(info.c));
ptr += strlen(info.c);如何用
' '填充剩余的指针位置
发布于 2011-06-08 05:42:56
您可以使用memset(3)用空格填充内存区域:
size_t total_size = get_total_size(); // total size of array, in bytes
size_t len = get_len(); // length of content, in bytes, <= total_size
assert(len <= total_size);
char *array = malloc(total_size);
// ... fill the first len bytes with your data
memset(&array[len], ' ', total_size - len); // and the rest to ' ' chars不过,这种方法也有一些问题。首先,除非仔细检查该len < total_size,否则很容易受到缓冲区溢出的影响。第二,听起来像是要将它用作字符串,在这种情况下,您需要注意保留一个拖尾的空'\0‘字符。
https://stackoverflow.com/questions/6274534
复制相似问题