Click to See Complete Forum and Search --> : Array


Taggi
January 18th, 2003, 12:10 PM
Hello.

I have a problem with arrays... well surprising isn't it? *g*

I have declared a struct with 5 member variables.

Now I created an Array of this sruct with 5 Objects of this struct.

Later I want in my programm to copy this 5 objects into another array, which is an array of this struct too.

Now my problem: how?

Sure you can type for each object and Member:
SecondArray[i].FirstMemberVar = FirstArray[i].FirstMemberVar;
SecondArray[i].SecondMemberVar = FirstArray[i].SecondMemberVar;
...

but is there another way without defining a copycontructor? Something linke CopyMemory or strcpy with chars?

Or something like this:
two arrays with 5 objects each, have to be copied in one array with 10 objects. How do I do this?

Taggi

DanM
January 18th, 2003, 12:18 PM
If you have just PODs it is pretty easy (if you have pointers to any memory that also needs to be copied, this solution does not apply !!!).

Ex:

struct MyStruct
{
int n1;
int n2;
};

MyStruct array1[5], array2[5], array3[10];

//init array1
//init array2

memcpy(array3, array1, 5 * sizeof(MyStruct));
memcpy(array3 + 5, array2, 5 * sizeof(MyStruct));

Dan

Taggi
January 18th, 2003, 12:25 PM
Thanks... but... what are PODs?

And no, there aren't unfortunatally any pointers..

I did not know, that memcpy works for non chars too...

But a little question at the end:

memcpy(array3 + 5, array2, 5 * sizeof(MyStruct));

+5 mean , that the first 5 objects/elements arent changed, right?

And:
how do I enlarge an array for example, from array1[10] to array[20] ?

Taggi

DanM
January 18th, 2003, 12:38 PM
plain old data, if I'm not worng :)
Yes, they are not changed.
memcpy is for void*, strcpy requires char*.
These arrays (by they way they are defined) cannot be enlarged. You may want to use std::vector if you need to grow the arrays.
Or you can just reinvent the wheel and write your own array class (most probably you don't need to do this unless you have some specific requirements that std::vector cannot satisfy).

Dan

Taggi
January 19th, 2003, 09:53 AM
Hello.

Are DWORD elements POD?

I will first look at std::vector in the documentation, but when something is not clear, I will Ask.. ;-P

Thanks for any help

Taggi

hiccup
January 19th, 2003, 10:04 AM
realloc(void*, size_t) will dynamically enlarge your array while retaining the original data provided the array is simple data types and was dymamically allocated to begin with. No guarantee it will live at the same memory location. Look at the help documentation for usage.

DanM
January 19th, 2003, 11:29 AM
Yes, DWORD is a POD type.
I simply forgot about realloc. It must be because of too many new/delete calls :)

Dan