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 avoid *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], i.e.,*struc[i]would change what one of those 10 pointers thatmain()allocated points to, but they haven’t been set yet. That’s the job here.And with those changes it works pretty well…