C const 指向 const struct 数组的指针作为函数参数

标签 c arrays pointers reference

我如何通过传递数组指针并在 Alt.1 中获取所请求的数组引用来使 Alt.1 按预期工作?

struct mystruct
{
    int id1;
    int id2;
};

const struct mystruct local_struct[] = {
    {0, 55},
    {1, 66},
};

// Alt.1 i like to make this work (not working)
int get_reference_1(const struct mystruct *s){

   s = local_struct;
   return 0;
}

// Alt.2 works perfect but i like to use the return as status as in Alt.1.
const struct mystruct *get_reference_2(){
   return local_struct;
}

int main()
{
  struct mystruct *s = NULL;

  // Alt.1
  if(get_reference_1(s))
     /* Expected Fail*/
  else
     /* Expected Success*/

  // Alt.2
  s = get_reference_2()
  if(!s)
     /* Expected Fail*/
  else
     /* Expected Success*/

  return 0;
}

也许我想错了,我需要传递一个双指针?

编辑:更正为“const”。 Edit2:更新标题。

最佳答案

s = local_struct; 正在更改局部变量 - 它不会更改 main 中的变量。传递变量的地址并对取消引用它的原始变量进行更改。

int get_reference_1(struct mystruct **s){

   *s = local_struct;
   return 0;
}

调用它会是

  if(get_reference_1(&s))
     /* Expected Fail*/
  else
     /* Expected Success*/

您还通过将 const 变量分配给非 const 变量而让编译器报错。这里的 local_struct 是在您的代码中声明的常量 struct。解决方案检查你是否在做正确的事情——这个分配是否必要?您还可以根据需要添加 const 限定符:

int get_reference_1(const struct mystruct **s){
   *s = local_struct;
   return 0;
}
...
const struct mystruct *s = NULL;

在最坏的情况下,删除 const 限定符。

关于C const 指向 const struct 数组的指针作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48829188/

相关文章:

python - python 中 'for loops' 的替代方案,运行速度很快

只有指针才能保存 NULL 值吗?

c - 对 C 结构不熟悉,有人可以帮我定义这些结构吗?

c - 访问/释放动态分配的结构数组时出现不需要的行为

c++ - 使用 C++ 方式对结构和数组进行别名处理

python - str.format(**arg) 可以用来检查格式吗?

c - 如何从 C 中的二进制文件中读取两种不同的数据类型?

c++ - 将 '_' 更改为 ' ' 根本不起作用

c# - 将二维数组拆分为包含新行的数组

c - 调用的参数太少