[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppMemcpy
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.
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):
Don't use memcpy on non-plain-old-data types [2].
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
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.
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); } }
- include <cstring>
- include <cstdio>
- include <cassert>
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):
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; }
- include <iostream>
- include <cstdio>
- include <cstring>
- include <cassert>
Don't use memcpy on non-plain-old-data types [2].
'memcpy' links
Code links
Reference
- 1) C++ International Standard. ISO/IEC 14882. Second edition. Table 99
- 2) Herb Sutter and Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6, chapter 96: don't memcpy and memcmp non-POD's
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
