1

I'm just learning C, and I'm having problems assigning an array to a globally defined array in a function:

// So I have my multi-dim global array
uint16_t pulseSets[1][50][2];

void foo()
{
   //create another array to work with in here
   uint16_t pulses[50][2];

   // Do some stuff with pulses here
   // ...

   // and now assign it to my global array
   pulseSets[0] = pulses;

}

When compiling I get the error:

incompatible types when assigning to type ‘uint16_t[50][2]’ from type ‘uint16_t (*)[2]’

 pulseSets[0] = pulses;
              ^

Both arrays are of the same type and size, so why is this breaking?

user2166351
  • 183
  • 1
  • 1
  • 9

2 Answers2

1

Why it's breaking, it's because 'pulses' is considered a pointer (missing []).

A way around it would be to use a struct like this:

typedef struct {
  uint16_t Pulses[ 50 ][ 2 ];
} Pulse;

Pulse pulseSets[ 2 ];

void foo()
{
   //create another array to work with in here
   Pulse pulses;

   // Do some stuff with pulses here
   // ...
   memset( pulses, 0, sizeof(pulses));

   // and now assign it to my global array
   pulseSets[ 0 ] = pulses;
}
damorin
  • 1,389
  • 1
  • 12
  • 15
0

In C, array memory allocations are treated as constant pointers and cannot be re-assigned after their creation.

Thus, your global declaration uint16_t pulseSets[1][50][2]; created 100 ints that pulseSets[0] points to, but pulseSets[0] cannot be reset to point at some other location in memory.

You have 2 options: 1. copy the data from pulses[50][2] to pulseSets[0] in a nested for loop (which involves 100 int copies) 2. declare your global pulseSets[1][50][2] as a pointer to the two-dimensional array and use dynamic memory allocation in foo() to assign to it as such:

int **pulseSets[2];

void foo()
{
   //create another array to work with in here
    int **pulses = new int[50][];
    for (int i = 0;i<50;i++)
        pulses[i] = new int[2];

   // Do some stuff with pulses here
   // ...

   // and now assign it to my global array

   pulseSets[0] = pulses;
}
Jonathan
  • 1,349
  • 1
  • 10
  • 20