Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly use memcpy?

Tags:

c

I have a mainbuf[bufsize], empty initially.

I am reading from some input : read(fd, otherbuf, sizeof(otherbuf)) different strings which are assigned to otherbuf. Every time I assign a new string to otherbuf I want to append it to mainbuf.

I do:

memcpy(mainbuf,otherbuf, numberofBytesReadInotherbuff) but it does not give me all the strings. Usually the last otherbuf is right, but all the other ones are missing characters.

like image 204
user461316 Avatar asked Apr 07 '11 20:04

user461316


People also ask

How to use memcpy () function in C language?

The C library function void *memcpy (void *dest, const void *src, size_t n) copies n characters from memory area src to memory area dest. Following is the declaration for memcpy () function. dest − This is pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*.

What is the declaration for memcpy () function?

Following is the declaration for memcpy () function. dest − This is pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*.

What is the required header for the memcpy function?

In the C Language, the required header for the memcpy function is: #include <string.h>.

What is the difference between memcpy () and SRC ()?

Following is the declaration for memcpy () function. dest − This is pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*. src − This is pointer to the source of data to be copied, type-casted to a pointer of type void*.


1 Answers

You need to change the destination pointer each time you call memcpy.

For example, suppose you have 4 bytes in mainbuf now. Next you receive 10 bytes. Here is how to append it:

memcpy(mainbuf + 4, otherbuf, 10);
like image 86
Donotalo Avatar answered Sep 23 '22 06:09

Donotalo