简体   繁体   中英

C const pointer to const struct array as function argument

How can i make Alt.1 to work as intended by passing a pointer of an array and get the requested reference of an array in 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;
}

Maybe i'm thinking wrong and i need to pass a double pointer?

Edit: Corrected with 'const'. Edit2: Updated header.

s = local_struct; is changing a local variable - it won't change the one in main. Pass the address of the variable and make changes to the original variable dereferencing it.

int get_reference_1(struct mystruct **s){

   *s = local_struct;
   return 0;
}

Calling it would be

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

Also you are making the compiler complain by assigning a const variable to non-const one. Here the local_struct is a constant struct declared in your code. Solution check whether you are doing the right thing - is this assignment necessary? You could also add const qualifiers as needed:

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

In the worst case drop the const qualifier.

Here you go what you want

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

It will execute successfully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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