[英]Copy a matrix/2d array to another in c++
I am trying to copy a 2d array into another 2d array, i have these two array created: 我试图将一个2d数组复制到另一个2d数组中,我创建了这两个数组:
#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, but currentStage[][]
isn't, and i want to assign the values of secondStage
to currentStage
. 现在,我的secondStage[][]
数组上填充了值,但没有填充currentStage[][]
,我想将secondStage
的值分配给currentStage
。 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" 1 IntelliSense:无法使用“ char”类型的值初始化“ char(&)[20] [50]”类型的引用(非const限定)
2 IntelliSense: argument of type "char" is incompatible with parameter of type "char (*)[50]" 2 IntelliSense:“ char”类型的参数与“ char(*)[50]”类型的参数不兼容
How could I fix this? 我该如何解决?
change the assignment sentence in your for-loop: 在for循环中更改赋值语句:
arrayA[mapXcor][mapYcor] = arrayB[mapXcor][mapYcor];
by 通过
arrayA[a][b] = arrayB[a][b];
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: 评论:
man 3 memcpy
. 检查man 3 memcpy
。 #define ROWS 2
#define COLS 2
void copyArray(char (&arrayA)[ROWS][COLS], const char (&arrayB)[ROWS][COLS] ) {
memcpy(arrayA, arrayB, sizeof(arrayB));
}
int main(void){
char arr1 [ROWS][COLS];
char arr2 [ROWS][COLS];
// init arr1
copyArray(arr2, arr1);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.