gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:10:03 26 4
gpt4 key购买 nike

我有一个整数数组 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com