如何返回函数内部分配空间的结构体数组cpp

 1 #include "stdafx.h"
 2 #include <memory>
 3 #include <iostream>
 4 
 5 using namespace std;
 6 
 7 typedef struct _CTX
 8 {
 9     int a;
10     bool b;
11     char c;
12 }CTX;
13 
14 
15 void create_and_init_ctx(CTX * ctx[])
16 { 
17     for (int i = 0; i < 5; i++)
18     {
19         ctx[i] = (CTX *)malloc(sizeof(CTX));
20         ctx[i]->a = i+1;
21         ctx[i]->b = false;
22         ctx[i]->c = 'a' + i;
23     }
24 }
25 
26 void create_and_init_ctx_1(CTX ** ctx)
27 {
28     for (int i = 0; i < 5; i++)
29     {
30         ctx[i] = (CTX *)malloc(sizeof(CTX));
31         ctx[i]->a = i + 6;
32         ctx[i]->b = true;
33         ctx[i]->c = 'a'- 32 + i;
34     }
35 }
36 
37 void * create_and_init_ctx_2()
38 {
39     void * ctx = malloc(5*sizeof(CTX));
40     CTX *ctx_tmp = (CTX *)ctx;
41     for (int i = 0; i < 5; i++)
42     {
43         (ctx_tmp + i)->a = i + 10;
44         (ctx_tmp + i)->b = false;
45         (ctx_tmp + i)->c = 'g' + i;
46     }
47 
48     return (void *)ctx;
49 }
50 
51 
52 int main()
53 {
54     CTX * ctx[5];
55     create_and_init_ctx(ctx);
56     for (int i = 0; i < 5; i++)
57     {
58         cout << ctx[i]->a << "  " << ctx[i]->b << "  " << ctx[i]->c << endl;
59     }
60 
61     cout << endl;
62 
63     CTX * ctx_1[5];
64     create_and_init_ctx_1(ctx_1);
65     for (int i = 0; i < 5; i++)
66     {
67         cout << ctx_1[i]->a << "  " << ctx_1[i]->b << "  " << ctx_1[i]->c << endl;
68     }
69 
70     cout << endl;
71 
72     void * abc = create_and_init_ctx_2();
73 
74     CTX * ctx_2 = (CTX *)abc;
75     for (int i = 0; i < 5; i++)
76     {
77         cout << (ctx_2 + i)->a << "  " << (ctx_2 + i)->b << "  " << (ctx_2 + i)->c << endl;
78     }
79 
80     cout << endl;
81     return 0;
82 }

 

posted @ 2015-08-28 11:10  杂烩饭2012  阅读(250)  评论(0)    收藏  举报