unsigned long
is different size if you are using different operating system.
On 32 bit machines, usually unsigned long is 32 bit (4 bytes).
On 64 bit, usually unsigned long is 64 bit (8 bytes).
On top of that, it depends what is the C/C++ compiler. E.g. What is true for some compiler, might be not true for another.
Last I do not see where you release the memory you allocated with new
.
Here is your code using sizeof():
#include <iostream>
#include <string.h>
int main(){
unsigned long id = 12;
unsigned long age = 14;
size_t size = sizeof(unsigned long);
unsigned char* pData = new unsigned char[2*size];
memcpy(pData, &id, size);/* using memcpy to copy */
pData = pData + size;
memcpy(pData, &age, size);/* using memcpy to copy */
std::cout<<*reinterpret_cast<unsigned long*>(pData)<<std::endl;
pData = pData - size;
std::cout<<*reinterpret_cast<unsigned long*>(pData)<<std::endl;
// do you need to release the dynamic memory?
delete pData;
return 0;
}
Hope this helps. Comment if I miss something.
UPDATE:
I seems to missread the code. I am updated the code.
I will give you updated version where pointer arithmetic is used:
#include <iostream>
#include <string.h>
int main(){
unsigned long id = 12;
unsigned long age = 14;
unsigned long* pData = new unsigned long[2];
memcpy(pData, &id, sizeof(unsigned long));/* using memcpy to copy */
pData++;
memcpy(pData, &age, sizeof(unsigned long));/* using memcpy to copy */
std::cout<<*reinterpret_cast<unsigned long*>(pData)<<std::endl;
pData--;
std::cout<<*reinterpret_cast<unsigned long*>(pData)<<std::endl;
// do you need to release the dynamic memory?
delete pData;
return 0;
}
If I was you, I would do it like this - e.g. no sizeof, no & (address of).
#include <iostream>
#include <string.h>
int main(){
unsigned long id = 12;
unsigned long age = 14;
unsigned long *pData = new unsigned long[2];
pData[0] = id;
pData[1] = age;
std::cout << pData[1] << std::endl;
std::cout << pData[0] << std::endl;
delete pData;
return 0;
}
Hope this helps. Comment if I miss something.
I saw the comment for Windows / Microsoft C++ and size of unsigned long. This might be true, but I still think sizeof() is the way to do it. With sizeof() code is more portable and might compile to different platform, even on platforms you have no knowledge about.