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:
我有一个函数需要const some_type **作为参数(some_type是一个结构,函数需要一个指向这种类型数组的指针)。我声明了some_type *类型的局部变量,并对其进行了初始化。然后我将函数称为f(&some_array),编译器(gcc)说:
error: invalid conversion from ‘some_type**’ to ‘const some_type**’
What's the problem here? Why can't I convert a variable to const?
这有什么问题?为什么我不能将变量转换为const?
3 个解决方案
#1
11
See: Why can't I pass a char **
to a function which expects a const char **
? from the comp.lang.c FAQ.
请参阅:为什么我不能将char **传递给期望const char **的函数?来自comp.lang.c FAQ。
#2
1
You have a few options to get around what jamesdlin outlined in his answer.
你有几个选择来解决jamesdlin在他的回答中概述的内容。
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
.
你可以改变f的参数。
void f(some_type const* const* some_array);
#3
1
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:
尝试制作变量const:
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.
这读作“some_array是指向const some_type的指针”。代码无法修改指向的东西。因此,在将变量const传递给函数之前,必须先声明它。
(Edited...)
#1
11
See: Why can't I pass a char **
to a function which expects a const char **
? from the comp.lang.c FAQ.
请参阅:为什么我不能将char **传递给期望const char **的函数?来自comp.lang.c FAQ。
#2
1
You have a few options to get around what jamesdlin outlined in his answer.
你有几个选择来解决jamesdlin在他的回答中概述的内容。
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
.
你可以改变f的参数。
void f(some_type const* const* some_array);
#3
1
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:
尝试制作变量const:
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.
这读作“some_array是指向const some_type的指针”。代码无法修改指向的东西。因此,在将变量const传递给函数之前,必须先声明它。
(Edited...)