附加两个 void* 指针

发布于 2024-12-14 12:10:03 字数 580 浏览 2 评论 0原文

有没有办法追加 2 个 void* ptr?每个都是一个字符数组:

例如:

void * ptr;
ptr = malloc(3);
read(0, ptr, 3);

void * rtr;
rtr = malloc(3);
read (0, rtr, 3);

/*how to add ptr and rtr??*/

谢谢!

*编辑:是的,我想将内容添加在一起。 实际上,这更多的是我的代码的工作方式:

void *ptr;
ptr = malloc(3);
read(0, ptr, 3);

void *rtr;
rtr = malloc(1);
int reader;
reader=read(0, rtr, 1);
int i=1;
while(reader!=0){
  /* append contents of rtr to ptr somehow?? */
  i++;
  rtr = realloc(rtr, i);
  reader=read(0, rtr, 1);
}

我正在从文件中读取。文件可能会发生变化,如果文件发生变化,我必须逐字节附加。

Is there a way to append 2 void* ptr? Each is an array of chars:

For example:

void * ptr;
ptr = malloc(3);
read(0, ptr, 3);

void * rtr;
rtr = malloc(3);
read (0, rtr, 3);

/*how to add ptr and rtr??*/

Thank you!

*EDIT: YES, I would like to add the contents together.
In actuality this is more of how my code works:

void *ptr;
ptr = malloc(3);
read(0, ptr, 3);

void *rtr;
rtr = malloc(1);
int reader;
reader=read(0, rtr, 1);
int i=1;
while(reader!=0){
  /* append contents of rtr to ptr somehow?? */
  i++;
  rtr = realloc(rtr, i);
  reader=read(0, rtr, 1);
}

I'm reading from a file. And the file might change, I have to append byte-by-byte if the file changes.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

掩饰不了的爱 2024-12-21 12:10:03

您的问题并没有真正回答您的措辞方式,但我会尝试...

您必须首先使用 malloc() 分配一块内存。然后,你的 void 指针将指向它。该块将具有确定的大小。第二块符合相同的概念,并且具有确定的大小。

为了将第二个块附加到第一个块,应该为第一个块分配足够的额外空间来附加第二个块的内容。然后,您可以使用 memcpy() 将字节从第二个块复制到第一个块。您需要使用字节指针的转换来指定第一个块的偏移量。

((unsigned char *)(ptr) + ptr_alloced_bytes) 将是第一个块到第一个复制数据末尾的偏移量,其中 ptr_alloced_bytes 是第一个操作读取的字节数。

否则,您需要分配一个足够大的新块来容纳这两个块,然后使用 memcpy() 复制它们。

Your question doesn't really have an answer for the way you worded it, but I'll try...

You must allocate a block of memory first, using malloc(). Then, your void pointer would point to that. That block would have a definite size. The second block conforms to the same concepts, and has a definite size.

In order to append the second to the first, the first block should have been allocated with enough extra space to append the second block's contents. You would then use memcpy() to copy the bytes from the second block to the first block. You would need to use a cast to a byte pointer to specify the offset into the first block.

((unsigned char *)(ptr) + ptr_alloced_bytes) would be the offset into the first block to the end of the first copied data, where ptr_alloced_bytes is the number of bytes read by the first operation.

Otherwise you would need to allocate a new block that is large enough to hold both blocks, then copy them both using memcpy().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文