簡體   English   中英

將結構指針數組作為C中的ref傳遞

[英]passing an array of pointers of struct as a ref in C

我想做的事情如下:

struct mystruct {
   char *info;
};

// here is where I'm not sure how to
void do_something(struct mystruct **struc){
    int i;
    for (i = 0; i < 10; i++){
       *struc[i] = (struct mystruct *) malloc (sizeof (struct mystruct));
       *struc[i]->info = "foo";
    } 
}
int main(int argc, char *argv[]){
    struct mystruct **struc;

    struc = (struct mystruct **struc) malloc (sizeof(struct mystruct *struc) * 10);

    dosomething(&struc);
    // do something with struc and its new inserted values
    return 0;
}

我不確定如何將其作為參考傳遞,因此可以在dosomething()之后使用它

謝謝

好的,這是我的更正版本。 特別...

第26行:沒有理由拋出malloc(3)的結果,它已經返回一個void *

第28行:不要通過傳遞&struc來創建無意義的三重間接指針,因為您已經為其分配了空間,因此很難想象有任何可能的理由來對其進行更改。 您希望最終將malloc(3)的確切返回值傳遞給下一層。

第11行:另一種不必要的強制轉換,我們確實想更改struct[i]處的行指針,即*struc[i]會更改main()分配的那10個指針中的一個指針,但是它們沒有尚未設定。 這就是這里的工作。

通過這些更改,它可以很好地運行...

 1  #include <stdio.h>
 2  #include <stdlib.h>
 3  
 4  struct mystruct {
 5    char *info;
 6  };
 7  
 8  void do_something(struct mystruct ** struc) {
 9    int i;
10    for (i = 0; i < 10; i++) {
11      struc[i] = malloc(sizeof(struct mystruct));
12      struc[i]->info = "foo";
13    }
14  }
15  
16  void do_something_else(struct mystruct ** s) {
17    int i;
18  
19    for (i = 0; i < 10; ++i)
20      printf("%2d: %s\n", i, s[i]->info);
21  }
22  
23  int main(int argc, char *argv[]) {
24    struct mystruct **struc;
25  
26    struc = malloc(sizeof(struct mystruct *) * 10);
27  
28    do_something(struc);
29    do_something_else(struc);
30    return 0;
31  }

而不是dosomething(&struc); ,使用dosomething(struc); 你有一個struct mystruct ** ,這就是函數所期望的。

代替

*struc[i] = (struct mystruct *) malloc (sizeof (struct mystruct));

采用

struc[i] = (struct mystruct *) malloc (sizeof (struct mystruct));

struc是一個struct mystruct ** ,所以struc[i]將期望struct mystruct *

考慮不要生成malloc,因為它是void *:

http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1047673478&id=1043284351

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM