3

I have four uint8_t arrays:

uint8_t arrayOne[12]   = { 0x00,0x01,0x00,0x00,0x00,0x06,0xFE,0x03,0x01,0xC1,0x00,0x01 };

uint8_t arrayTwo[12]   = { 0x00,0x01,0x00,0x00,0x00,0x06,0xFE,0x03,0x4E,0x2D,0x00,0x0C };

uint8_t arrayThree[12] = { 0x00,0x01,0x00,0x00,0x00,0x06,0xFE,0x03,0x01,0xF3,0x00,0x01 };

uint8_t arrayFour[12]  = { 0x00,0x01,0x00,0x00,0x00,0x06,0xFE,0x03,0x20,0x04,0x00,0x01 };

and I want them to add to another array:

uint8_t theArray[4][12] = { arrayOne,arrayTwo,arrayThree,arrayFour };

but the values of arrays change when I add them to theArray.

Why? How could I add them to array properly?

Noam M
  • 3,156
  • 5
  • 26
  • 41
Roo
  • 613
  • 1
  • 7
  • 24
  • Please specify what you want to do: copy them into a single 2d array, or create an array[4] of these array [pointers]. "Add" has too wide meaning here. (Both strategies already answered, btw.) – user3125367 Jun 03 '15 at 10:09

3 Answers3

4

The toplevel array should just be an array of pointers:

uint8_t *theArrays[] = { arrayOne,arrayTwo,arrayThree,arrayFour };

You will lose information about the lengths of each "row", but that's fine.

I don't think you can reference an array in the initializer like in your example and have the elements copied into a larger array automatically.

unwind
  • 391,730
  • 64
  • 469
  • 606
3

You have to copy each array in the result array using standard function memcpy declared in header <string.h>. For example

#include <string.h>
#include <stdint.h>

//...

uint8_t * arrayPtrs[] = { arrayOne, arrayTwo, arrayThree, arrayFour };

for ( size_t i = 0; i < sizeof( theArray ) / sizeof( *theArray ); i++ )
{
    memcpy( theArray[i], arrayPtrs[i], sizeof( theArray[i] ) );
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

You are trying to initialize an uint8_t array with pointers to uint8_t, not uint8_t elements.

try this:

uint8_t *theArrays[] = { array1,array2, ... };
Noam M
  • 3,156
  • 5
  • 26
  • 41