memcpy - First 2 elements in the new array are 8 and 255 [solved]

Hello.

As the title suggests, when I copy an array, the first two elements of the copy become 8 and 255. I'm using a 2D array and an Arduino Mega.

Array definition - The values are just for testing purpose, generally those will be HEX values for data and address of some registers.

const uint8_t E1_OTP0[3][10] = {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},                
                               {10, 11, 12, 13, 14, 15, 16, 17, 18, 19},       
                               {20, 21, 22, 23, 24, 25, 26, 27, 28, 29}};

I'm coppying with this:

for(int i = 0; i < 3; ++ i)
{
memcpy(arr_temp1[i], E1_OTP0[i], sizeof(E1_OTP0[0]));
}

The print out:

print_test(arr_temp1, reg_size_OTP);

void print_test(uint8_t HEX_read_dat1[][10], int arr_s){

for(int j = 0; j < 3; j++){

    Serial.print("Data ");
    Serial.print(j);
    Serial.print(": ");

  for(int i = 0; i < arr_s; i++){

    Serial.print(HEX_read_dat1[j][i]);
    if (i < (arr_s - 1)){Serial.print(", ");}
  }
  Serial.println(".");
}
}

I'm using 32 such 2D arrays/matrixes that's why I'm using the temporary array. The print out happens in 3 rows, 2nd and 3rd are fine but the 1st one has 8 and 255 in stead of 0 and 1.

Thank you for any tips and sollutions :slight_smile:

What does arr_temp look like?

And sizeof(E1_OTP0[0]) returns the size of the pointer which is either 1 or 2 (I'm not sure).

arduino_new:
What does arr_temp look like?

And sizeof(E1_OTP0[0]) returns the size of the pointer which is either 1 or 2 (I'm not sure).

uint8_t arr_temp1[3][10];

And when I print out:

            Serial.println(sizeof(arr_temp1[0]));
            Serial.println(sizeof(E1_OTP0[0]));

Both write out 10 which is correct.

change ++i to i++ in your for() loop

arduino_new:
change ++i to i++ in your for() loop

for(int i = 0; i < 3; i ++){

Same result, I still get 8, 255, 2, 3, 4... in the first line.

Rhydm:
I'm coppying with this:

Why? The for-loop is superfluous.

memcpy(arr_temp1, E1_OTP0, sizeof(arr_temp1));

Done.

I'm new to arrays so I was using an example.

Also thanks. It now works fine :slight_smile: +1 Karma

edit: Also the temporary array can be larger than the one I'm copying. I just set the size of the temporary one as the largest original one I have.
I've redone it with the for loop now and it works... might have had an index missmatch.