using memcpy and void*

This is a discussion on using memcpy and void* within the C++ Programming forums, part of the General Programming Boards category; My program below compiles perfectly. But the result is not as expected. That is quite common. The program works fine ...

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    4

    using memcpy and void*

    My program below compiles perfectly. But the result is not as expected. That is quite common. The program works fine when the data(&temp) is of type char, but problem arises when it is of type int. Pls advice what went wrong.

    #include <iostream.h>
    #include <iostream>
    #include <cstdlib>
    #include <stdio.h>
    #include <string>
    #include <malloc.h>
    using namespace std;

    class data {
    unsigned long int d_size;
    unsigned short int d_type;
    void* d_data;
    public:
    data();
    void setData(void* data, unsigned long int size, unsigned short int type);
    const void* getData();
    unsigned long int getDataSize();
    unsigned short int getDataType();
    };

    data::data() {
    d_size = 0;
    d_type = 0;
    d_data = NULL;
    }

    void data::setData(void* data, unsigned long int size, unsigned short int type) {
    d_data = malloc(size);
    memcpy(d_data, data, size);
    d_size = size;
    d_type = type;
    }

    const void* data::getData() {
    return d_data;
    }

    unsigned long int data::getDataSize() {
    return d_size;
    }

    unsigned short int data::getDataType() {
    return d_type;
    }

    const void* box1;
    unsigned long int box2;
    unsigned short int box3;

    int main()
    {
    data data_member[50];
    int temp = 23;

    data_member[0].setData(&temp, sizeof(int), 1);
    box1 = data_member[0].getData();
    box2 = data_member[0].getDataSize();
    box3 = data_member[0].getDataType();
    cout << (int*)box1 << " " << box2 << " " << box3 << endl;

    free((int*)box1);
    system("PAUSE");
    return 0;
    }

  2. #2
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    >But the result is not as expected.

    What is the expected result? Does replacing your output statement with -

    cout << *(int*)box1 << " " << box2 << " " << box3 << endl;

    give the expected result?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Disagreement about memcpy
    By ch4 in forum C Programming
    Replies: 9
    Last Post: 05-28-2009, 11:12 AM
  2. Replies: 14
    Last Post: 06-28-2006, 02:58 AM
  3. Memcpy(); Errors...
    By Shamino in forum C++ Programming
    Replies: 4
    Last Post: 03-24-2006, 11:35 AM
  4. memcpy with 128 bit registers
    By grady in forum Linux Programming
    Replies: 2
    Last Post: 01-19-2004, 06:25 AM
  5. memcpy
    By doubleanti in forum C++ Programming
    Replies: 10
    Last Post: 02-28-2002, 04:44 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21