Hi I would like to understand how memcpy works when dealing with a sequence of characters and integers
the definition of memcpy is the following:
Code:
void * memcpy ( void * destination, const void * source, size_t num );
so having the destination and the source, we copy num bytes from the source(which is an address in the main memory) to the address pointed by the variable destination
so we have
source points to A(which is an address)
destination points to B(address)
let's say num = 3
we copy 3 bytes which start from A address and finish in some address A + x to the B address
so finally we will have B + x reserved for the 3 bytes correct?
suppose we have this code
Code:
#include <iostream>
using namespace std;
int main(void){
char* a = "123";
int value = 0;
memcpy(&value, a, sizeof(int));
cout<<a<<endl;
cin.get();
return 0;
}
I want to copy the number 123 to the integer value
which works fine but when I try to do the opposite, it doesn't
Code:
#include <iostream>
using namespace std;
int main(void){
char* a = "";
int value = 1234;
memcpy(a, &value, sizeof(int));
cout<<a<<endl;
cin.get();
return 0;
}
it gives me an exception
if I use an array instead
Code:
#include <iostream>
using namespace std;
int main(void){
char a[4] = "";
int value = 1234;
memcpy(a, &value, sizeof(int));
cout<<a<<endl;
cin.get();
return 0;
}
it gives me the same exception...
the exception is access violation writing location 0x0034234..
can someone please explain me why?
Thanks in advance