David Mändlen David Mändlen - 3 years ago 106
C++ Question

c++11 memcpy data from one int* to another int*

I have a class:

class Kunde{
char *name;
char *ort;
int *alter;
double umsatz;
int transaktion;
int id=0;
int dummyAlter=20;

public:
static int anzahl;

Kunde(char* n=(char*)"Max Maier", char* o=(char*)"Köln", int *a=&dummyAlter);
Kunde(const Kunde &k);
~Kunde();
void buy(double u);
static int getAnzahl();
};


In my .cpp-File I have:

Kunde::Kunde(char* n, char* o, int *a)
{
name=n;
ort=o;
alter=a;
id=anzahl++;
umsatz=0;
transaktion=0;
};


and I want to write a copying constructor.

This is achieved by:

Kunde::Kunde(const Kunde &k)
{
int lenname=(int)strlen(k.name)+1;
name=new char[lenname];
memcpy(name, k.name, lenname);
int lenort=(int)strlen(k.ort)+1;
ort=new char[lenort];
memcpy(ort, k.ort, lenort);

alter=new int;
memcpy(alter, k.alter, sizeof(int));

id=k.id;
anzahl++;
umsatz=k.umsatz;
transaktion=k.transaktion;
}


The code compiles just fine but when I execute it, it produces an error where I use memcpy to copy the data from k.alter to alter.

Do you see what is wrong? I tried stfw and rtfm but it seems I'm too stupid to find anything concerning "pure" int*'s instead of int*-Arrays.

Thanks for your time.

Answer Source

After some hints from you folks I finally found the problems.

  1. First: I always tried to save the char*s directly (you see this in the constructor) and by that only achieved that I had pointers to my strings.

Solution:

Kunde::Kunde(char* n, char* o, int a)  
{
    int lenname=(int)strlen(n)+1;
    name=new char[lenname];
    memcpy(name, n, lenname);

    int lenort=(int)strlen(o)+1;
    ort=new char[lenort];
    memcpy(ort, o, lenort);

    alter=new int;
    *alter=a;
    id=anzahl++;
    umsatz=0;
    transaktion=0;
}
  1. Second: I tried to use an int* as a parameter for the constructor which a) makes no sense and b) is a royal PITA. After I fixed my parameters I used the construct proposed by @Matthias247 to do the copying of the int-data.

Solution:

Kunde::Kunde(const Kunde &k) 
{
    int lenname=(int)strlen(k.name)+1;
    name=new char[lenname];
    memcpy(name, k.name, lenname);

    int lenort=(int)strlen(k.ort)+1;
    ort=new char[lenort];
    memcpy(ort, k.ort, lenort);

    alter=new int;
    *alter = *(k.alter);
    id=k.id;
    anzahl++;
    umsatz=k.umsatz;
    transaktion=k.transaktion;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download