[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppMemcpy

(C++) memcpy

Standard function [1] to copy raw memory.

std::memcpy(void * dest, const void * const src, const int nBytes)


Below is an example that shows the copying op a C-style string using both std::strcpy and std::memcpy. Note the first being easier as std::strcpy relies on a C-style string being null-terminated.

  1. include <cstring>
  2. include <cstdio>
  3. include <cassert>
int main() { char myArray[4] = {'\0'}; { //Using std::strcpy std::strcpy(myArray,"yes"); assert(std::strcmp(myArray,"yes")==0); std::printf("myArray: '%s'\n",myArray); } { //Using std::strcpy std::memcpy(myArray,"no\0",(std::size_t)sizeof(char) * 3); assert(std::strcmp(myArray,"no")==0); std::printf("myArray: '%s'\n",myArray); } }


You can use it to copy a plain-old-data type to e.g. an array of char (which then can be copied to a full-fledged std::string):

  1. include <iostream>
  2. include <cstdio>
  3. include <cstring>
  4. include <cassert>
struct MyStruct { char name[12]; // No terminator char date[8]; // No terminator char age[2]; // No terminator }; int main() { // Create a struct MyStruct m; // Create an array char a[sizeof(MyStruct) + 1] = { '\0' }; { // Some compile-time asserts { const char temp[ (sizeof(m.name ) == 12 ? 1 : 0) ]; } { const char temp[ (sizeof(m.date ) == 8 ? 1 : 0) ]; } { const char temp[ (sizeof(m.age ) == 2 ? 1 : 0) ]; } { const char temp[ (sizeof(MyStruct) == 22 ? 1 : 0) ]; } } // Initialize the struct std::memcpy(m.name,"Bilderbikkel",sizeof(m.name)); // No terminator std::memcpy(m.date,"20070509",sizeof(m.date)); // No terminator std::memcpy(m.age,"26",sizeof(m.age)); // No terminator // Copy the struct to the array std::memcpy(a,&m,sizeof(MyStruct)); // Add a terminator to the array a[sizeof(MyStruct)] = '\0'; // print the array std::printf("%s\n",a); std::cout << a << std::endl; }


Don't use memcpy on non-plain-old-data types [2].

'memcpy' links

Code links

Reference



last edited (June 1, 2007) by bilderbikkel, Number of views: 3295, Current Rev: 6 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.