GodzillaQ
GodzillaQ

Reputation: 23

C++ Copy structure without pointer

I want to copy data structure into another one

struct times{
    QString name;
    double time1;
    double time2;
    double time3;
};

/..../

times *abc = new times[10];
times *abc2 = new times[10];

How can I copy abc into abc2 without copying a pointers?

Upvotes: 1

Views: 718

Answers (4)

Umang Modi
Umang Modi

Reputation: 11

Simple, It is same as assigning char pointer.

struct TestStruct
{
int a;
float c;
char b;
};

main()
{
    struct TestStruct *structa = new TestStruct;

    structa->a = 1121;
    structa->b = 'D';
    structa->c = 12.34;

    struct TestStruct *abc = structa;
    cout<<abc->a;
}

Upvotes: 0

Tamil Maran
Tamil Maran

Reputation: 291

Alternatively you can use a copy constructor in your struct.

struct times{
    times(const &A) {
        this->name = A.name;
        this->time1 = A.time1;
        this->time2 = A.time2;
        this->time3 = A.time3;
    }
};

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254461

std::copy(abc, abc+10, abc2);

although, unless you've got a very good reason for juggling raw pointers, use a friendlier container:

std::vector<times> abc(10);
std::vector<times> abc2 = abc;  // copy-initialisation
abc2 = abc;                     // copy-assignment

Upvotes: 5

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133004

for(int i = 0; i < 10; ++i)
   abc2[i] = abc[i];

or, alternatively

std::copy_n(abc, 10, abc2);

Upvotes: 1

Related Questions