C pointer to a 2-dimensional array

I have problems with a pointer to a two-dimensional array. The pointer must point to an array of variable sizes.

// create pointer to 2 dimensional array
TimeSlot **systemMatrix; // this is a global variable

In the function, I want to create a new array.

void setup(uint16_t lines, uint16_t coloumns) {
    // create 2 dimensional array. size can be set here.
    TimeSlot tmpTimeSlots[lines][coloumns];

    // make the pointer point to this array
    systemMatrix = tmpTimeSlots; // WARNING
}

But when I point to a pointer to an array, the compiler says “warning: assignment from an incompatible type of pointer”. In addition, the microcontroller in which the software runs receives a hard error when accessing the system matrix [2] [5] from another function.

The systemMatrix variable is required later when accessing tmpTimeSlots elements.

I tried combinations like

systemMatrix = *(*tmpTimeSlot);

etc., but none of them work.

Any help is appreciated :) Thanks!

EDIT: Well, the problem is clear and resolved, thanks a lot!

+1
source share
5 answers

!= .

, , . - , . , TYPE arr[sz]; return arr;.

const size_t width = 3;
const size_t height = 5;
TimeSlot tmpTimeSlot[width][height];

systemMatrix = malloc(width * sizeof systemMatrix[0]);
for (int i = 0; i < width; i++) {
    systemMatrix[i] = malloc(height * sizeof systemMatrix[i][0]);
    for (int j = 0; j < height; j++) {
        systemMatrix[i][j] = tmpTimeSlot[i][j];
    }
}
+6

systemMatrix 2D-, . : TimeSlot (*systemMatrix)[columns]; - 2D-. columns ( C99) (pre-C99).

, .

+4

.

 TimeSlot **systemMatrix;

C ( ); , ( C-, ). , , :

 TimeSlot (* systemMatrix)[lines];

lines, ( . ). lines , .

systemMatrix , , , , - systemMatrix , setup .

. .

, , , ( sizeof(int *) malloc); . . ( ) .

free , !

+2

( ) . , .

. : 2D- ( ), , ( , ).

+1

:

  • . , . malloc(). , , , , , , . undefined C.
  • Unlike your statement, it TimeSlot **systemMatrix;does not declare a two-dimensional array, but a pointer to a pointer to Timeslot. See the comp.lang.c FAQ for dynamically creating multidimensional arrays.
+1
source

All Articles