我有一个指针,指向在运行时动态填充的数组。在收集和存储数组之后,我希望数组的所有剩余缓冲区位置都填充空空间。我怎么能这么做?
根据一些评论:
以下是我所拥有的:
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‘字符。
发布于 2011-06-08 05:33:11
这就是我从你的问题中解释出来的
int Array[20];
int *p=Array;
int no,i,len;
char ch=' ';
len=sizeof(Array)/sizeof(int)
printf("Enter no of elements ");
scanf("%d",&no);
for(i=0;i<no;i++)
scanf("%d",p+i);
for(i=no;i<len;i++)
p[i]=(int )ch;希望这能有所帮助。
发布于 2011-06-09 01:32:07
我认为最干净的方法是在分配数组并将ptr分配到buf的开头之后。只需使用' '填充所有内容,使用memset()即可。
char buf[50];
char *ptr = buf;
memset (ptr, ' ', sizeof(buf)); // like this
// If this buffer is meant to be printed to the screen or used as a string,
// it's probably better to write the end-of-string character at the last
// position of the buffer:
buf[49] = 0;
// operations to write stuff on the buffer因此,在操作结束时,所有尚未使用的缓冲区的其余位置都将有' '。
编辑:
我一直在考虑您要求的内容,除非您有非常具体的理由来填充数组中的空空间,这通常不是我们处理这种情况的方法(请参阅下面的评论)。
char* tmp_string = "**Copy Me**";
printf("Size of string:%d\n", strlen(tmp_string));
char buf[50];
printf("Size of buf:%d\n", sizeof(buf));
memset(buf, 0, sizeof(buf)); // cleaning the entire buffer
char *ptr = buf;
strncpy(ptr, tmp_string, strlen(tmp_string));
ptr += strlen(tmp_string);
*ptr = '!';
printf("Size of buf after copy: %d\n", strlen(buf));
printf("Result: %s\n", buf);输出:
Size of string:11
Size of buf:50
Size of buf after copy: 12
Result: **Copy Me**!注意到,复制后buf的大小为12,这是因为我们在操作开始时对缓冲区进行了零化(即用\0填充缓冲区)。在缓冲区中\0的第一个符号时,printf()停止迭代数组和打印字符。
,但是,我可以想到一个很好的理由来解释为什么您不想要这种方法。下面是对上面代码的轻微修改。它用空空间填充缓冲区,并在缓冲区的最后一个位置添加字符串结束字符(\0)。注意到,最后字符串的大小不是12!它是49,因为您用有效字符填充了缓冲区。
char* tmp_string = "**Copy Me**";
printf("Size of string:%d\n", strlen(tmp_string));
char buf[50];
printf("Size of buf:%d\n", sizeof(buf));
memset(buf, ' ', sizeof(buf)); // cleaning the entire buffer with empty spaces
buf[49] = 0; // setting a \0 at the end of the string
char *ptr = buf;
strncpy(ptr, tmp_string, strlen(tmp_string));
ptr += strlen(tmp_string);
*ptr = '!';
printf("Size of buf after copy: %d\n", strlen(buf));
printf("Result: %s\n", buf);产出:
Size of string:11
Size of buf:50
Size of buf after copy: 49
Result: **Copy Me**!https://stackoverflow.com/questions/6274534
复制相似问题