Reputation: 6655
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.
Upvotes: 0
Views: 2615
Reputation: 708
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().
Upvotes: 2