簡體   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