简体   繁体   中英

assigning 2D array as a struct member

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]

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
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM