I am trying to initialize a multidimensional array in batches and can't seem to make it work or find an example!
The dimensions I am working with are big enough that I don't want to specify them by hand!
More precisely :
int test[5][192];
for(int i = 0; i < 5; i++){
int temp[192] = {...};
test[i] = temp;
}
// use variable test here..
I want to use this method because the temp array is dynamicaly defined depending on variable i.
Is this type of initialization possible?
Should the temp array be in dynamic memory?
Since after the initialization I pass a reference to the first element of test to another function and I am not in control of how the other function passes over the elements I need to keep the data type of an array!
-
You'll get an invalid array assignment if you do it like that i believe.Olivier Poulin– Olivier Poulin2015年06月23日 14:12:27 +00:00Commented Jun 23, 2015 at 14:12
-
Not duplicate since the goal is to keep the simple array data-typeMarleyzs– Marleyzs2015年06月23日 14:38:35 +00:00Commented Jun 23, 2015 at 14:38
4 Answers 4
If you want to copy the values of temp array , instead of "=", you should use memory copy
memcpy( test[i], temp, sizeof(temp[192]));
1 Comment
Arrays do not have the copy assignment operator. So this is impossible with arrays.
If you will dynamically allocate each row then in any case you have to store somewhere the number of their elements. So even dynamically allocated arrays are not suitable in this case when the numbers of elements in each row can differ.
You should use standard container std::vector<std::vector<int>> instead.
Comments
You dont use the second dimension in the array for the test array. you just write test[], but you must write test[][]. I thing you don't must use the temp array. You can initialize you array direct, without using a temp array.
I'm not absolutly sure, but memcpy are just using for one diemnsionalarrays ant not for multidimensional arrays
1 Comment
if you know, Temp and test[i] are two pointer which point to memory so if you print temp or test[i] you will see the address of where they start on memory. in your code you lose the address of test[i] because you changed pointer test[i] to temp and now both of them are pointing to the same place where temp begin on there!
Comments
Explore related questions
See similar questions with these tags.