[英]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()
我不确定如何将其作为参考传递,因此可以在
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 *
第26行:没有理由抛出
malloc(3)
的结果,它已经返回一个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. 第28行:不要通过传递&struc来创建无意义的三重间接指针,因为您已经为其分配了空间,因此很难想象有任何可能的理由来对其进行更改。 You want ultimately to pass the exact return value from
malloc(3)
down to the next layer. 您希望最终将
malloc(3)
的确切返回值传递给下一层。
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. 第11行:另一种不必要的强制转换,我们确实想更改
struct[i]
处的行指针,即*struc[i]
会更改main()
分配的那10个指针中的一个指针,但是它们没有尚未设定。 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);
而不是
dosomething(&struc);
, use dosomething(struc);
,使用
dosomething(struc);
. 。 You have a
struct mystruct **
, and that's what the function expects. 你有一个
struct mystruct **
,这就是函数所期望的。
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 *
. 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.