将非常量参数传递给C中的const函数参数 [英] Passing non-const arguments to const function parameters in C
问题描述
我有一个函数,该函数指定一个const参数来指示调用者它不会被修改:
I have a function that specifies a const parameter to indicate to the caller that it won't be modfied:
int func1(const char *some_string)
{
// Do something non-destructive with some_string
}
我将一个非常量变量作为参数传递给 func1
:
I pass a non-const variable as an argument to func1
:
int func2(void)
{
char *my_string = "my text";
func1(my_string);
}
gcc报告:
warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
$ b $中丢弃 const限定符b
应对这种情况的正确方法是什么?创建 my_string
的const副本似乎有点多,但是简单地投射似乎掩盖了警告。
What is the correct way to deal with this situation? Creating a const copy of my_string
seems a bit much, but simply casting seems like burying the warning.
推荐答案
您遇到的问题源于您的 main
函数。
The issue you're having stems from your main
function.
当您声明 char * my_string =我的文本;
,您正在创建指向字符串文字的非常量指针。按照设计,字符串文字如我的文本
是不可变的,因此在语言中为const。 (在实践中,编译器通常将字符串文字放入包含只读存储器的可执行文件的特定部分中,因此尝试使用非const指针修改文字可能导致segfault。)
When you declare char *my_string = "my text";
,you are creating a non-const pointer to a string literal. By design, string literals such as "my text"
are immutable, and therefore const in the language. (In practice, the compilers usually put the string literals into a specific section of the executable which contains read-only memory, so attempting to modify the literal using the non-const pointer can lead to a segfault.)
通过声明一个指向字符串文字的非常量指针,您最终得到一个指针,您可以使用该指针修改不可变的字符串文字,这被认为是未定义的行为
By declaring a non-const pointer to the string literal, you end up with a pointer which you could use to modify the immutable string literal, which is considered undefined behavior in C.
请参见有关更多信息。
See this question for more information.
解决此问题的最简单方法是简单地更改将char * my_string
转换为 const char * my_string
。
The easiest way to solve this is to simply change char *my_string
into const char *my_string
.
这篇关于将非常量参数传递给C中的const函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!