Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly initialize a const int const * variable?

So I have a struct:

typedef struct myStruct
{
    const int *const array_ptr;
} myStruct_s;

I have a const array of int:

const int constArray[SIZE1] =
{
        [0] = 0,
        [1] = 1,
        [2] = 2,
        //...
};

Now I have a const array of myStruct_s initialized with designated intializers:

const myStruct_s structArray[SIZE2] =
{
        [0] =
            {
                    .array_ptr = &constArray
            },
        //...
}

I get the warning:

a value of type "const int (*)[SIZE1]" cannot be used to initialize an entity of type "const int *const"

How can I properly initialize this pointer?

I'd like to avoid:

const myStruct_s structArray[SIZE2] =
{
        [0] =
            {
                    .array_ptr = (const int *const) &constArray
            },
        //...
}

If possible, since I feel like I tell the compiler "I don't know what I am doing, just don't check the type please"...

Thanks for your help :).

like image 969
Plouff Avatar asked Apr 21 '16 10:04

Plouff


1 Answers

constArray is already (decays into) a pointer, you want

.array_ptr = constArray

or

.array_ptr = &constArray[0] /* pointer to the first element */

instead of

.array_ptr = &constArray /* you don't want the address of */

Consider

int a[] = {1,2};
int *p = &a;

This is not correct because p wants a pointer to an int (&a[0] or simply a), not a pointer to an array of 2 int (&a)

like image 148
David Ranieri Avatar answered Oct 21 '22 07:10

David Ranieri