1 #include<iostream>
2 using namespace std;
3
4
5 int arrayInit(int size, int **outbuf)
6 {
7 int a;
8 int *buf = NULL;
9 buf = (int *)malloc(sizeof(int)*size);
10 memset(buf, 0, size);
11 *outbuf = buf;
12
13 cout << "请赋值:" << endl;
14 for (int i = 0; i < size; i++)
15 {
16 cin >> a;
17 buf[i] = a;
18 }
19 cout << "赋值结束!" << endl;
20 // buf[0] = 2;
21 return size;
22 }
23
24 void arrayExpand(int *inbuf, int presize, int **outbuf)
25 {
26 int size=2*presize;
27 int *buf = NULL;
28 // presize = _msize(inbuf) / sizeof(int);
29
30 buf = (int*)malloc(sizeof(int)*size);
31 memset(buf, 0, size);
32
33 for (int i = 0; i < presize; i++)
34 {
35 buf[i] = inbuf[i];
36 }
37 // buf[1] = 0;
38 *outbuf = buf;
39
40 }
41
42 int arrayAdd(int *inbuf,int a,int presize)
43 {
44 int maxSize = 0;
45 int size = presize + 1;
46 maxSize = _msize(inbuf) / sizeof(int);
47
48 cout << "maxsize====>" << maxSize << endl;
49 if (size > maxSize)
50 {
51 arrayExpand(inbuf, presize, &inbuf);
52 cout << "扩容了===》" << size << endl;
53 }
54
55 inbuf[presize] = a;
56
57 return size;
58 }
59
60 void main()
61 {
62 int size = 0;
63 int *buf=NULL;
64 // int *outbuf = NULL;
65 size = arrayInit(1, &buf); //初始化长度为1的数组
66
67 // arrayExpand(buf, size, &buf); //扩容函数,把容量扩为原来的两倍
68
69 size = arrayAdd(buf, 5, size); //在数组最后添加数字5 在添加函数中,扩容后数字添加不成功???
70 cout << "size[1]" << buf[1] << endl;
71 size = arrayAdd(buf, 6, size); //在数组最后添加数字6
72 cout << "size[2]" << buf[2] << endl;
73 cout << "size=" << buf[1] <<endl;
74 cout << "maxsize" << _msize(buf)/sizeof(int) << endl;
75 system("pause");
76 }