如果我通过 gcc 编译以下代码(在文件 “myfile.c” 中):
void bar(int *pi)
{
/* do something */
}
foo(const int *pi)
{
bar(pi);
}
使用以下命令行:
gcc myfile.c -ansi -pedantic-errors
我收到以下错误:
error: passing argument 1 of 'bar' discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]
bar(pi);
note: expected 'int *' but argument is of type 'const int *'
void bar(int *pi)
我的问题是,在不改变命令行的情况下,如何避免这个错误? e.i.只需在 foo
中编写一些代码,因为我无法更改 bar
和 foo
原型(prototype)。
最佳答案
首先,const
-ness 可以被丢弃,只要实际指针指向非const
位置:
foo(const int *pi) {
bar((int*)pi); // <<== Be very careful with this!
}
这里的假设是 pi
实际上是一个非 const
指针,所以最好的做法是让编译器通过删除 const 来强制执行它
来自 foo
的声明:
void foo(int *pi) { // Remove const
...
}
如果你不能那样做,并且由于 bar
接受一个没有 const
限定符的 int
指针,你需要将它传递给一个可以被写。例如,如果这是单个项目,而不是数组,您可以复制指针指向的内容,并将其传递给函数:
void bar(int *pi, size_t n) {
/* do something */
}
foo(const int *pi) {
int tmp = *pi;
bar(&tmp);
}
如果 pi
指向一个包含 n
元素的数组,您需要为它创建一个临时缓冲区:
void bar(int *pi, size_t n) {
/* do something */
}
foo(const int *pi, size_t n) {
int *buf = malloc(sizeof(int) * n);
memcpy(buf, pi, sizeof(int) * n);
bar(buf, n);
free(buf);
}
关于c - 如何在 C 中从 const 类型显式转换为类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45420489/