struct sample {
int x;
int y;
int arr[10];
};
int arr2[10] = {0, 1, 2, 4, 3, 2, 2, 1, 5, 5};
int a = 19;
int b = 22;
struct sample* samp = new sample;
samp->x = a;
samp->y = b;
samp->arr = ??
In the above example, I need to initialize array inside the structure arr[10] with the elements of arr2[10].
How to do it in C++??
You cannot assign an array (here b ) by a pointer to the first element of another array (here a ) by using b = a; in C. The syntax doesn't allow that.
struct->array1[0] = (unsigned char) something; ... struct->array1[3] = (unsigned char) something; Just wondering if there is a way to initialize all 4 values in one line. SOLUTION: I needed to create a temporary array with all the values initialized, then call memset() to copy the values to the struct array.
An array can be initialized at the time of its declaration. In this method of array declaration, the compiler will allocate an array of size equal to the number of the array elements. The following syntax can be used to declare and initialize an array at the same time. // initialize an array at the time of declaration.
How to do it in C++??
The simplest solution is to use std::copy
as was said by others. Do not use memcpy
in C++, as std::copy
does the same for PODs but also is applicable for non-PODs and just Does The Right Thing. If the type in your array changes one day, you would have to revisit all places where you do such a copy and replace the memcpy
. (And you will miss one of the places and have a hard time to find the bug). Using memcpy
in C++ has no benefits, so use std::copy
from the start.
The better solution would be to use C++ data structures, in this case, use std::array
#include <array>
struct sample {
int x;
int y;
std::array<int, 10> arr; //C++ array instead of plain C array
};
int main()
{
std::array<int, 10> arr2 = {0, 1, 2, 4, 3, 2, 2, 1, 5, 5};
int a = 19;
int b = 22;
// 1: no need to say "struct sample*" since C++98
// 2: prefer to use smart pointers..
//sample* samp = new sample;
std::unique_ptr<sample> samp(new sample());
samp->x = a;
samp->y = b;
samp->arr = arr2; //it's as easy as it should be!
// 3: ... so ypu can't forget to delete!
//delete samp;
}
Edit: I used unique_ptr here, although in this little example you don't need to use heap allocation at all. To bring in Grijesh's initialization in as well:
int main()
{
std::array<int, 10> arr2 = {0, 1, 2, 4, 3, 2, 2, 1, 5, 5};
int a = 19;
int b = 22;
sample samp = {a, b, arr2}; //done!
}
no allocation, no cleanup, no element-wise assignment needed.
you can use memcpy:
memcpy(sample->arr,arr2,sizeof(int) * 10)
But I would suggest using std::vector for both.
Copy array using for loop,
for(int i=0; i<10; i++) {
samp->arr[i]=arr2[i];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With