简体   繁体   中英

Store int value into char* - C++?

I have allocated a block of memory as (char *), in which I want to be able to store an integer.

char * arr = new char[50];
int num = 9;

for(int i = 0; i < sizeof(int); i++)
{
      *((int *)arr) = arr[i];
}

memcpy(&arr, &num, sizeof(num));

cout<<"Contents of arr: "<<arr<<endl;    

I seem to be getting a segmentation fault whenever I compile however. How can I fix this? Thank you!

The for loop is unnecessary. I'm not sure what it is trying to accomplish. The memcpy is ok except that you're taking the address of arr which is already a pointer. This will work:

char * arr = new char[50];
int num = 9;

memcpy(arr, &num, sizeof(num));

cout<<"Contents of arr: "<< ((int *)arr) <<endl;

Perhaps your for loop was trying to do this:

char * arr = new char[50];
int num = 9;

*((int *)arr) = num;

cout<<"Contents of arr: "<< ((int *)arr) << endl;

That would be ok, too.

Edit: The contents of the array are not printable directly, at least not with any meaning (and may crash because of no zero termination). Assuming you want it to look like an integer, I've edited the code above. C++ purists will probably object to using a C style cast instead of reinterpret_cast<>, but that's a separate issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM