C语言实现动态数组的问题
那位大侠帮忙看看,为什么不能实现动态增加?
1 #include<stdio.h>
2 #include<stdlib.h>
3
4 int insert(char (**namep)[20], int (**scorep)[5],unsigned int *np,
5 char *namebuf, int *scorebuf)
6 {
7 char (*temp_name)[20] = NULL;
8 int (*temp_score)[5] = NULL;
9
10 if ( (namep==NULL) || (scorep==NULL) || (np==NULL)
11 || (namebuf==NULL) || (scorebuf==NULL))
12 {
13 return -1;
14 }
15
16 temp_name = (char (*)[20])malloc(sizeof(char(*)[20])*(*np+1));
17
18 if (temp_name == NULL)
19 {
20 return -1;
21 }
22
23 temp_score = (int (*)[5])malloc(sizeof(int(*)[5])*(*np+1));
24
25 if (temp_score == NULL)
26 {
27 free(temp_name);
28 return -1;
29 }
30 free(temp_name);
31
32 temp_name = *namep;
33 free(temp_score);
34 temp_score = *scorep;
35
36 memcpy(temp_name, *namep, sizeof(char(*)[20])*(*np));
37 temp_name += *np;
38 memcpy(temp_score, *scorep, sizeof(int(*)[5])*(*np));
39 temp_score += *np;
40
41 memcpy(temp_name, namebuf, sizeof(char(*)[20])*(*np+1));
42 memcpy(temp_score, scorebuf, sizeof(int(*)[5])*(*np+1));
43
44 *np +=1;
45 return 0;
46
47 }
48
49 void print(char (*name)[20], int (*score)[5], int n)
50 {
51 int i, j;
52 printf("\tsubject1 subject2 subject3 subject4 subject5\n");
53
54 for (i=0; i<n; i++)
55 {
56 printf("%s", name[i]);
57
58 for (j=0; j<5; j++)
59 {
60 printf("%9d",score[i][j]);
61 }
62
63 printf("\n");
64 }
65
66 }
67
68 int main(void)
69 {
70 char (*name)[20] = NULL;
71 int (*score)[5] = NULL;
72 unsigned int n=0;
73 int a, i;
74 char *namebuf = NULL ;
75 int *scorebuf = NULL;
76
77
78 while (1)
79 {
80 printf("\t\tmemu\n");
81 printf("1.insert\n");
82 printf("2.print\n");
83 printf("3.exit\n");
84
85 scanf("%d", &a);
86 getchar();
87
88 if (a==1)
89 {
90 system("clear");
91 printf("input name:\n");
92 scanf("%s",namebuf);
93 getchar();
94
95 for (i=0; i<5; i++)
96 {
97 printf("input subjet%d:\n", i+1);
98 scanf("%d", scorebuf);
99 getchar();
100 }
101
102 insert(&name, &score, &n, namebuf, scorebuf);
103 }
104
105 else if (a==2)
106 {
107 system("clear");
108 print(name,score, n);
109 }
110
111 else if (a==3)
112 {
113 break;
114 }
115
116 else
117 {
118 printf("input error!\n");
119 }
120 }
121
122 return 0;
123 }