简体   繁体   中英

Const array and pointer to const

I just had a strange error on an old compiler (ColdFire 5703 MCCCF) and I want to confirm I understood correctly the C standard relative to pointer to const and const arrays (let's say in C99 even if this compiler is older).

Say I have this function:

void func(const unsigned char *cst_ptr);

and the array:

const unsigned char array[xx] = {...};

So array is an array where every element is const .

Then if I do:

func(array)

then array is equivalent to &array[0] so the object passed in parameter is of type const unsigned char * hence the prototype of the function is respected.

Is it correct ?

const unsigned char *cst_ptr it is not a const pointer only the pointer to const unsigned char .

When you use the array as a parameter of the function, the array decays to a pointer to fist element of the array. If the array was declared as having const unsigned char elements it will match your function declaration.

OT:

The const pointer is declared another way:

unsigned char * const const_ptr;

if you want const pointer to const data:

const unsigned char * const const_ptr;

Yes, you are right, the type of the object passed as a parameter is const char * , because the whole var type is conserned by the const . so you gonna have something like cst_ptr = {[B][o][o][M][!]} that can't be changed by the futur. Hope this answers your question.

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