【发布时间】:2010-12-31 18:58:30
【问题描述】:
如果作为参数发送给函数,如何添加记录?
struct record {
char name[20];
int nr;
};
void AddRecord(struct record **p_allRecs, int p_size);
int main() {
struct record *allRecs;
/* putting in some records manually, size++... */
allRecs = (struct record *)malloc(size*sizeof(struct record));
}
AddRecord(&allRecs, size);/* wan't to add a record like this */
}/* end main */
void AddRecord(struct myRecord **p_allRecs, int p_size){
int i;
struct record *allRecsTemp; /* temporary */
allRecsTemp = (struct record *)malloc((p_size+1)*sizeof(struct record));/* oneup */
/* first copy existing recs */
for(i = 0; i < p_size; i++) {
strcpy(allRecsTemp[i].name, p_allRecs[i]->name);/* this want't work */
allRecsTemp[i].nr = p_allRecs[i]->nr;/* this want't work */
}
/* then ask for new record */
printf("Name?");
scanf("%s", &allRecssTemp[p_size].name);
printf("Nr? ");
scanf("%d", &allRecsTemp[p_size].nr);
p_size++;
free(p_allRecs);
p_allRecs = allRecsTemp;
【问题讨论】:
-
这看起来像是对 realloc 的笨拙重写。
-
这很笨拙,但是重写 realloc 也不是坏事,恕我直言。
标签: c parameters function struct