简体   繁体   中英

Passing an array of pointers as a const

What is the difference between a an array being passed as a constant versus the array values being constants?

When passing an array of pointers to a function when every value is a constant:

`void display(Fraction* const ar[], int size);`

everything works fine but when the array is a constant

`void display(const  Fraction* ar[], int size);` 

the compiler gives the following error when calling the function:

`error C2664: 'display' : cannot convert parameter 1 from 'Fraction *[3]' to 'const Fraction *[]'`

main:

int main()
{
    Fraction* fArray[3];
    Fraction* fOne = new Fraction();
    Fraction* fTwo = new Fraction();
    Fraction* fThree = new Fraction();
    fOne->num = 8;
    fOne->den = 9;
    fTwo->num = 3;
    fTwo->den = 2;
    fThree->num = 1;
    fThree->den = 3;
    fArray[0] = fOne;
    fArray[1] = fTwo;
    fArray[2] = fThree;
    display(fArray, 3);

    system("pause");
    return 0;
}

This is a FAQ .

Note that const T* a[] means T const* a[] , ie it's not the array itself that you have declared const ; instead you have declared an array of pointers to const items.

Essentially, if the language provided an implicit conversion T**T const** , then you could inadvertently attempt to change something that was originally declared const :

int const     v = 666;
int*          p;
int**         pp = &p;
int const**   ppHack = pp;    //! Happily not allowed!

*ppHack = &v;    // Now p points to the const v...

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