const array const {}

匆匆过客 提交于 2019-12-10 12:59:50

问题


So you can do this:

void foo(const int * const pIntArray, const unsigned int size);

Which says that the pointer coming is read-only and the integer's it is pointing to are read-only.

You can access this inside the function like so:

blah = pIntArray[0]

You can also do the following declaration:

void foo(const int intArray[], const unsigned int size);

It is pretty much the same but you could do this:

intArray = &intArray[1];

Can I write:

void foo(const int const intArray[], const unsigned int size);

Is that correct?


回答1:


No, your last variant is not correct. What you are trying to do is achieved in C99 by the following new syntax

void foo(const int intArray[const], const unsigned int size);

which is equivalent to

void foo(const int *const intArray, const unsigned int size);

That [const] syntax is specific to C99. It is not valid in C89/90.

Keep in mind that some people consider top-level cv-qualifiers on function parameters "useless", since they qualify a copy of the actual argument. I don't consider them useless at all, but personally I don't encounter too many reasons to use them in real life.




回答2:


Use cdecl. It gives an error on the second entry. The first only clearly suggests that the second const refers to the *.




回答3:


In C/C++, you cannot pass an entire array as an argument to a function. You can, however, pass to the function a pointer to an array by specifying the array's name without an index.

(E.g) This program fragment passes the address of i to func1() :

int main(void)
{
int i[10];
func1(i);
.
.
.
}

To receive i, a function called func1() can be defined as

void func1(int x[]) /* unsized array */
{
.
.
}

or

void func1(int *x) /* pointer */
{
.
.
}

or

void func1(int x[10]) /* sized array */
{
.
.
}

source : THE COMPLETE REFERENCE - HERBERT.



来源:https://stackoverflow.com/questions/7259948/const-array-const

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!