开发者

writing to a given void* memory location in C

I have a function that takes as one of its parameters "void* buffer". In this function, I need to write to that memory location. Ho开发者_JAVA百科wever, doing something like

*buffer = "Hello\0Hi\0";

doesn't work because I can't dereference a void* pointer. How do I put a string data into that memory location? Note that I need to copy data, not necessarily a string, as it may contain the null character.

Updated to reflect that strcpy is not enough


If you string "may contain the null character," then it isn't really a C string.

If you need to copy a certain number of bytes from one memory location to another, regardless of the contents, you can use memcpy. You can get the size of the string literal using sizeof (this size includes the final, implicit null terminator).


You can't use the assignment operator to copy a string. You'll need to use something like strcat (which, by the way, is VERY unsafe).

You're probably looking for

strcpy( (char *) buffer, "Hello");

Or better still, use strncpy. You absolutely need to pass in the size of the buffer and make sure you don't overrun it, or else you have a HUGE security hole in your application, not to mention the source of countless hard-to-trace bugs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜