Reputation: 333
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, but currentStage[][]
isn't, and i want to assign the values of secondStage
to 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"
2 IntelliSense: argument of type "char" is incompatible with parameter of type "char (*)[50]"
How could I fix this?
Upvotes: 2
Views: 18833
Reputation: 6298
#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;
}
Upvotes: 0
Reputation: 13046
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
.Upvotes: 2
Reputation: 13792
change the assignment sentence in your for-loop:
arrayA[mapXcor][mapYcor] = arrayB[mapXcor][mapYcor];
by
arrayA[a][b] = arrayB[a][b];
Upvotes: 3