Copy a matrix/2d array to another in c++
Solution 1
change the assignment sentence in your for-loop:
arrayA[mapXcor][mapYcor] = arrayB[mapXcor][mapYcor];
by
arrayA[a][b] = arrayB[a][b];
Solution 2
Code you probably are trying to reach. Do not show it to teacher :-) - there is too much from practical programming. Just look and then write your own solutions:
#include <string.h>
#include <stdio.h>
#define mapXcor 5
#define mapYcor 5
static char secondStage [mapXcor][mapYcor];
static char currentStage [mapXcor][mapYcor];
void populateArray(char (&arrayA)[mapXcor][mapYcor], const char (&arrayB)[mapXcor][mapYcor]) {
/*
for(int a = 0; a < mapXcor; ++a) {
for(int b = 0; b < mapYcor; ++b) {
arrayA[a][b] = arrayB[a][b];
}
}
*/
memcpy(arrayA, arrayB, sizeof(arrayB));
}
int main()
{
for(int a = 0; a < mapXcor; ++a) {
for(int b = 0; b < mapYcor; ++b){
currentStage[a][b] = a*b + 10*a;
}
}
populateArray(secondStage, currentStage);
for(int a = 0; a < mapXcor; ++a) {
for(int b = 0; b < mapYcor; ++b){
printf("%2i ", secondStage[a][b]);
}
printf("\n");
}
return 0;
}
Comments:
- You have bad array index limits in cycle. Look for corrected function under comment.
- You have wrong indexes in assignment in cycle. Again, commented out code.
- If you passed one array by reference (destination) why not to use constant reference for source?
- In practice as your areas have the same type (you could even define them as having the same type)
nobody copies them by elements. I have used memcpy() but this is only good if memory areas do not
overlap (in this case - yes). check
man 3 memcpy
. - Learn harder :-)
Daniel Sega
Updated on June 04, 2022Comments
-
Daniel Sega about 2 years
I am trying to copy a 2d array into another 2d array, i have these two array created:
#define mapXcor 50 #define mapYcor 50 char secondStage [mapXcor][mapYcor]; char currentStage [mapXcor][mapYcor]; //mapXcor and mapYcor are constant integers
Now my
secondStage[][]
array is populated with values on it, butcurrentStage[][]
isn't, and i want to assign the values ofsecondStage
tocurrentStage
. So i created the function bellow:void populateArray(char (&arrayA)[mapXcor][mapYcor], char arrayB[mapXcor][mapYcor]) { for(int a = 0; a < mapXcor + 1; ++a) { for(int b = 0; b < mapYcor + 1; ++b) { arrayA[mapXcor][mapYcor] = arrayB[mapXcor][mapYcor]; } } } populateArray(currentStage[mapXcor][mapYcor],secondStage[mapXcor][mapYcor]);
But when i use the function it gives me a error :
1 IntelliSense: a reference of type "char (&)[20][50]" (not const-qualified) cannot be initialized with a value of type "char"
2 IntelliSense: argument of type "char" is incompatible with parameter of type "char (*)[50]"
How could I fix this?