C语言 如何正确使用memcpy?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5587121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to properly use memcpy?
提问by user461316
I have a mainbuf[bufsize], empty initially.
我有一个mainbuf[bufsize],最初是空的。
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 otherbufI want to append it to mainbuf.
我正在从一些输入中读取:read(fd, otherbuf, sizeof(otherbuf))分配给otherbuf. 每次我分配一个新字符串时,otherbuf我都想将它附加到mainbuf.
I do:
我愿意:
memcpy(mainbuf,otherbuf, numberofBytesReadInotherbuff)but it does not give me all the strings. Usually the last otherbufis right, but all the other ones are missing characters.
memcpy(mainbuf,otherbuf, numberofBytesReadInotherbuff)但它没有给我所有的字符串。通常最后一个otherbuf是正确的,但所有其他的都缺少字符。
回答by Donotalo
You need to change the destination pointer each time you call memcpy.
每次调用 时都需要更改目标指针memcpy。
For example, suppose you have 4 bytes in mainbufnow. Next you receive 10 bytes. Here is how to append it:
例如,假设您mainbuf现在有 4 个字节。接下来您将收到 10 个字节。这是附加它的方法:
memcpy(mainbuf + 4, otherbuf, 10);
回答by mikehabibi
memcpy replaces memory, it does not append. If you want to use memcpy, your code will need to be a little more complex.
memcpy 替换内存,它不附加。如果您想使用 memcpy,您的代码需要稍微复杂一些。
void * memcpy ( void * destination, const void * source, size_t num );
void * memcpy ( void * destination, const void * source, size_t num );
When you pass in mainbuf, you are passing the same destination address each time. You need to increment the destination address everytime you use memcpy so that it places it in subsequent memory, instead of overwriting the same string each time.
当你传入 mainbuf 时,你每次都在传递相同的目标地址。每次使用 memcpy 时都需要增加目标地址,以便将其放置在后续内存中,而不是每次都覆盖相同的字符串。
Try using strcat instead, it is designed to concatenate strings together, which sounds like what you want to do. Make sure you check you have enough memory left before you use it, so you don't encounter memory issues.
尝试改用 strcat ,它旨在将字符串连接在一起,这听起来像是您想要做的。确保在使用之前检查您是否有足够的内存,这样您就不会遇到内存问题。
回答by wallyk
The description of the problem sounds like the appropriate use of strcat. Strcat must be handled with care since it can easily write beyond the bounds of a buffer. For that reason, here are variations like strncat()which can prevent buffer overruns—if used correctly.
问题的描述听起来像strcat. 必须小心处理 Strcat,因为它很容易超出缓冲区的边界进行写入。出于这个原因,这里有一些变体strncat(),如果使用得当,可以防止缓冲区溢出。

