Home > Mobile >  assigning 2D array as a struct member
assigning 2D array as a struct member

Time:11-24

I need to create a struct with a 2D bool array as member, so I made it double pointer as shown below. No I have a problem whenever I try to assign 2D array object to this struct member, I receive a warning that It's incompitable pointer type. Is there anyway to assign it (Not copy because I don't have an object only double pointer as a struct member)

#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>



typedef struct
{
    bool** object;
}entry_t;

bool testObject[3][6];

entry_t entry =
{
        .object = testObject
};

The warning received

warning: initialization of '_Bool **' from incompatible pointer type '_Bool (*)[6]' [-Wincompatible-pointer-types]

CodePudding user response:

A pointer-to-pointer is not an array. It is not a 2D array. It is not a pointer to an array. It can't be made to point at arrays.

A very special use-case of pointer-to-pointer is to have it point at the first member of an array of pointers. This is mostly just useful when declaring an array of pointers to strings.

bool testObject[3][6]; is a 2D array - an array of arrays. The first item is an array of type bool [6]. In order to point at it, you need a pointer of type bool (*)[6]. The correct code is therefore:

typedef struct
{
  bool (*object)[6];
}entry_t;

bool testObject[3][6];

entry_t entry =
{
  .object = testObject
};
  • Related