Home > Enterprise >  How to create a pointer to a buffer in a typedef struct in C?
How to create a pointer to a buffer in a typedef struct in C?

Time:11-26

I getting an incompatible-pointer-types error when trying to Initialize a typedef struct with a pointer to a char buffer. The struct looks like this:

typedef struct otCryptoKey
{
    const uint8_t *mKey;       ///< Pointer to the buffer containing key. NULL indicates to use `mKeyRef`.
    uint16_t       mKeyLength; ///< The key length in bytes (applicable when `mKey` is not NULL).
    uint32_t       mKeyRef;    ///< The PSA key ref (requires `mKey` to be NULL).
} otCryptoKey;

This is what i have tried, and i also tried to initialize with all the parameters in the struct.

    uint8_t mKey[16] = "1234567891012131";
    uint8_t *mKeyPointer = mKey;

    otCryptoKey *aKey = {mKeyPointer};

Can anyone figure out why i get this error?

CodePudding user response:

You're creating a pointer to a otCryptoKey and attempting to initialize it with a pointer to uint8_t. Those types are not compatible.

What you want is to create an otCryptoKey object and initialize the mKey member with that pointer.

otCryptoKey aKey = {mKey, sizeof mKey, 0};

CodePudding user response:

That syntax initializes a struct, not a pointer to a struct.

You should instead do: otCryptoKey aKey = {mKeyPointer};

Or better yet, use named fields and lose the intermediate variable: otCryptoKey aKey = { .mKey = mKey };

  • Related