c - 如何在 C 中从 const 类型显式转换为类型?

标签 c

如果我通过 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 中编写一些代码,因为我无法更改 barfoo 原型(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/

相关文章:

c++ - 多维对象的多维数组与仅包含一维对象的高维数组之间有什么区别

c - 墨西哥/Matlab : Accessing objectarray which is a member of another object

c - STM32:无法退出UART中断的中断处理程序

c++ - 让系统调用 `select()` 阻塞,直到套接字获得可读取的内容

c - 理解 pipe() 函数

c - 从 SDL 教程构建示例程序时出现 GCC 错误

java - C:以编程方式查找 JVM 库文件位置

c - Malloced char* 但崩溃并说它没有 malloc

c - 如何对 C 中的所有命令行参数求和?

c - 仅使用整数缩放值