开发者

'Invalid conversion from some_type** to const some_type**'

开发者 https://www.devze.com 2022-12-27 06:13 出处:网络
I\'ve got a function that requires const some_type** as an argument (some_type is a struct, and the function needs a pointer to an array of this type). I declared a local variable of type some_type*,

I've got a function that requires const some_type** as an argument (some_type is a struct, and the function needs a pointer to an array of this type). I declared a local variable of type some_type*, and initialized it. Then I call the function as f(&some_array), and the compiler (gcc) says:

error: invalid conversion from ‘some_type**’ to ‘const some_type**’

What's开发者_运维知识库 the problem here? Why can't I convert a variable to const?


See: Why can't I pass a char ** to a function which expects a const char **? from the comp.lang.c FAQ.


You have a few options to get around what jamesdlin outlined in his answer.

You could use an intermediate variable.

some_type const* const_some_array = some_array;
f(&const_some_array);

You could change the parameters of f.

void f(some_type const* const* some_array);


You probably need to specify some more context, for instance is the argument passed data into or out of (or both?) the function?

Try making your variable const as well:

some_type const *some_array = ....;

This reads as "some_array is a pointer to a const some_type". The code can't modify the thing being pointed at. So you have to declare your variable const before passing it to the function.

(Edited...)

0

精彩评论

暂无评论...
验证码 换一张
取 消