简体   繁体   中英

passing an array of pointers of struct as a ref in C

I would like to do something like:

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

I'm not sure how to pass it as a reference so I can make use of it after dosomething()

Thanks

Ok, here is my corrected version. Specifically...

Line 26: no reason to cast the result of malloc(3) , it already returns a void *

Line 28: don't make a pointless triple-indirect pointer by passing &struc, you have already allocated space for it so it's hard to imagine any possible reason to change it. You want ultimately to pass the exact return value from malloc(3) down to the next layer.

Line 11: another unnecessary cast, and we really do want to change the row pointer at struct[i] , ie, *struc[i] would change what one of those 10 pointers that main() allocated points to, but they haven't been set yet. That's the job here.

And with those changes it works pretty well...

 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  }

Instead of dosomething(&struc); , use dosomething(struc); . You have a struct mystruct ** , and that's what the function expects.

Instead of

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

Use

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

struc is a struct mystruct ** , so struc[i] will expect a struct mystruct * .

考虑不要生成malloc,因为它是void *:

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

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