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

时间:2018-02-16 14:46:59

标签: 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:更新了标题。

2 个答案:

答案 0 :(得分:3)

s = local_struct;正在更改本地变量 - 它不会更改主变量。传递变量的地址并更改原始变量,取消引用它。

int get_reference_1(struct mystruct **s){

   *s = local_struct;
   return 0;
}

调用它将是

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

此外,您通过将const变量分配给非常量变量来使编译器抱怨。这里local_struct是代码中声明的常量struct。解决方案检查您是否做了正确的事 - 这项任务是否必要?您还可以根据需要添加const限定符:

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

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

答案 1 :(得分:2)

在这里,你想要你想要的东西

struct mystruct
{
    int id1;
    int id2;
};

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

// Alt.1 i like to make this work (not working)
int get_reference_1(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.
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;
}

它会成功执行。