繁体   English   中英

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

[英]C const pointer to const struct array as function argument

我如何通过传递数组的指针并在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; 正在更改局部变量-不会更改主变量。 传递变量的地址,并更改对原始变量的引用。

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限定符。

在这里你想要的东西

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;
}

它将成功执行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM