I am trying to get pointers to work with multi dimensional arrays. I got it to work no problems with normal arrays but when I use pointers with multi dimensional arrays, I end up getting different values with the pointer that from the actual array. I wrote an example for this:
//Just setting up Array Sizes
#define Array1_Size 5
#define Array2_Size1 5
#define Array2_Size2 5
void setup() {
//Begin Serial for debuging
Serial.begin(115200);
//Set up the array and the pointer for the array:
uint8_t Array1[Array1_Size];
uint8_t *Array1_Point = Array1;
//Setting random number to the array just for something to compare:
for (uint8_t X = 0; X < Array1_Size; X++)
Array1[X] = random(255);
//Printing out all of the random values we generated using the actual Array:
Serial.println(F("Array Contents:"));
for (uint8_t X = 0; X < Array1_Size; X++) {
Serial.print(Array1[X]);
if (X != Array1_Size - 1) Serial.print(",");
}
Serial.println();
//Printing out all of the random values we generated using the pointer to the Array:
//it prints out correctly just like the array
Serial.println(F("Pointer to Array Contents:"));
for (uint8_t X = 0; X < Array1_Size; X++) {
Serial.print(Array1_Point[X]);
if (X != Array1_Size - 1) Serial.print(",");
}
Serial.println(); Serial.println(); Serial.println();
//Setting up MultiDimensional array and pointer, similar but slightly different:
uint8_t Array2[Array2_Size1][Array2_Size2];
uint8_t **Array2_Point = (uint8_t**)Array2;
//Setting up random numbers again
for (uint8_t X = 0; X < Array2_Size1; X++) {
for (uint8_t Y = 0; Y < Array2_Size2; Y++) {
Array2[X][Y] = random(255);
}
}
//Printing out all contents from actual array:
Serial.println(F("MultiDimensional Array Contents:"));
for (uint8_t X = 0; X < Array2_Size1; X++) {
for (uint8_t Y = 0; Y < Array2_Size2; Y++) {
Serial.print(Array2[X][Y]);
if (Y != Array2_Size2 - 1) Serial.print(",");
}
Serial.println();
}
Serial.println();
//Printing out all contents from Pointer to the array:
//This ends up printing completely different values from the actual array
Serial.println(F("Pointer to MultiDimensional Array Contents:"));
for (uint8_t X = 0; X < Array2_Size1; X++) {
for (uint8_t Y = 0; Y < Array2_Size2; Y++) {
Serial.print(Array2_Point[X][Y]);
if (Y != Array2_Size2 - 1) Serial.print(",");
}
Serial.println();
}
Serial.println();
}
void loop() {
}
And this is what I get on Serial Monitor:
Array Contents:
232,19,158,38,175
Pointer to Array Contents:
232,19,158,38,175
MultiDimensional Array Contents:
197,114,68,188,109
120,80,102,47,102
143,142,79,160,52
3,124,114,32,70
18,189,123,116,190
Pointer to MultiDimensional Array Contents:
92,169,252,250,29
238,219,240,211,131
255,207,191,29,190
173,250,221,229,191
31,227,186,230,151
Can someone please help, I want to know what I am doing wrong here.
I suspect it has something to do with how I declare the pointer or maybe how I get the address to the pointer.