abhi312
abhi312

Reputation: 362

Store value in pointer var

How to store int values in *pData and display values from it?

  int id = 12;
  int age = 14;
  unsigned char* pData = new unsigned char[8];
  memcpy(pData,&id,4);/* using memcpy to copy */
  pData = pData + 4;
  memcpy(pData,&age,4);/* using memcpy to copy */
  // How to print value from buffer *pData

Upvotes: 1

Views: 235

Answers (5)

mystic_coder
mystic_coder

Reputation: 472

You can print pData using reinterpret_cast operator :

#include <iostream>
#include <cstring>

int main(void)
{
    int id = 12;
    int age = 14;
    const size_t size = sizeof(int);
    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<int*>(pData)<<std::endl;
    pData = pData - size;
    std::cout<<*reinterpret_cast<int*>(pData)<<std::endl;
    delete []pData;
    return 0;
}

Upvotes: 1

M.M
M.M

Reputation: 141608

After using memcpy to copy the bytes of an int into an unsigned char buffer, the only correct way to display the ints is to copy the bytes back into an int. For example:

int temp_int;
memcpy(&temp_int, pData, sizeof temp_int);
std::cout << temp_int << '\n';
memcpy(&temp_int, pData + sizeof temp_int, sizeof temp_int);
std::cout << temp_int << '\n';

Attempting to reinterpret the buffer as an int would cause undefined behaviour by violating the strict aliasing rule.

Upvotes: 2

pstanisz
pstanisz

Reputation: 181

If you really need to allocate memory as unsigned char*, you can do it like below:

#include <iostream>
#include <cstring>

using namespace std;

int main() {
    int id = 12;
    int age = 14;

    // const pointer to buffer which can contain 2 ints
    unsigned char* const pData = new unsigned char[2*sizeof(int)];

    // non-const pointer to operate on data
    unsigned char* pDataPtr = pData;

    memcpy(pDataPtr,&id,sizeof(int));
    pDataPtr += sizeof(int);
    memcpy(pDataPtr,&age,sizeof(int));

    std::cout<<*reinterpret_cast<int*>(pData)<<std::endl;
    std::cout<<*reinterpret_cast<int*>(pData + sizeof(int))<<std::endl;

    delete [] pData;

    return 0;
}

Upvotes: 1

Madhu Kumar Dadi
Madhu Kumar Dadi

Reputation: 735

memcpy(pData,&id,4);

This line copies the four bytes data in id to pData as int but you declared it as char * . if you declare it as int *pData = new int[2]; then you can ptint exact values.

 using namespace std;
 int id = 12;
 int age = 14;
 unsigned int* pData = new unsigned int[2];
 memcpy(pData,&id,4);
 pData = pData + 1;
 memcpy(pData,&age,4);
 pData = pData - 1;
 cout<<"ID:"<<pData[0]<<"\nAge:"<<pData[1]<<endl;

This will print the values.

Upvotes: 2

kiviak
kiviak

Reputation: 1103

you can change pData into int *, then you can print the int valve.


cout<<*((int *)pData);

Upvotes: 2

Related Questions