gpt4 book ai didi

c - 如何在C语言的函数中添加记录(结构体)?

转载 作者:行者123 更新时间:2023-11-30 14:31:06 26 4
gpt4 key购买 nike

如果将记录作为参数发送给函数,如何添加记录?

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;

最佳答案

在 C 中,可以对结构体进行赋值。因此,您可以这样说:

allRecsTemp[i] = (*p_allRecs)[i];

不需要调用 strcpy() 等。这样做应该会简化您的代码。哦,还有:

free(p_allRecs);
p_allRecs = allRecsTemp;

应该是:

free( * p_allRecs );
* p_allRecs = allRecsTemp;

记住 - p_allRecs 是指向指针的指针,而 allRecsTemp 只是一个指针。

关于c - 如何在C语言的函数中添加记录(结构体)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1991667/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com