c - 函数调用中指向 const 的指针

标签 c pointers constants

我有一个整数数组 int foo[3],我想将它传递给另一个函数。我想完成两件事:

  • 通过引用传递
  • 将其设置为常量,因为它不应被修改。

我定义的函数是:

void print_foo(const int(*const foo)[3]) {

    // Print the second integer
    printf("%d\n", (*foo)[1]);
}

我称它为:

int foo[3] = {1, 2, 3};

print_foo(&foo);

当我用 MinGW 的 gcc 编译它时,我收到警告:

warning: passing arg 1 of `print_foo` from incompatible pointer type

我想了解我做错了什么。

注意: 我可以在没有第一个 const 的情况下隐藏声明函数的警告:

void print_foo(int(*const foo)[3])

但这似乎是一种解决方法,因为我不仅希望指针地址保持不变,而且希望内存的内容保持不变(这就是两个 const 的原因)。

最佳答案

就这样做吧:

#include <stdio.h>

// note can also use "const int foo[3]" but in that
// case 3 is nothing more than a comment for a reader
void print_foo(const int foo[])
{
  // Print the second integer
  printf("%d\n", foo[1]);
}

int main()
{
  int foo[3] = {1, 2, 3};

  print_foo(foo);
}

数组已经由地址给出

关于c - 函数调用中指向 const 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54822497/

相关文章:

c++ - 内存寻址与数组的混淆

c - C 中 int fpurge() 和 int fflush() 的区别

c - 为什么数组的地址等于它在 C 中的值?

c - 访问超出分配的空间并且不会出现段错误

c++ - 为什么允许我从 const 成员函数调用 this->deviceContext->map()?

sql - Oracle SQL 查询中的常量

php - 使用包含常量名称的简单变量访问类常量

c++ - 在 Windows 上制作一个带有拉丁字符 (Á ,ò ,ã ) 的简单程序

编译Ruby报错: Failed to configure openssl. 不会安装

c++ - 输出逻辑错误