简体   繁体   English

如何使用C编程语言在函数中添加记录(结构)?

[英]How to add records (struct) in a function in the C programming language?

How do you add a record if you send as a parameter to a function? 如果作为参数发送给函数,如何添加记录?

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;

In C, structs can be assigned. 在C语言中,可以分配结构。 You can therefore say things like: 因此,您可以这样说:

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

No need for calls to strcpy() etc. Doing this should simplify your code. 无需调用strcpy()等。这样做可以简化您的代码。 Oh, and: 哦,还有:

free(p_allRecs);
p_allRecs = allRecsTemp;

should be: 应该:

free( * p_allRecs );
* p_allRecs = allRecsTemp;

Remember - p_allRecs is s pointer to a pointer, while allRecsTemp is just a pointer. 记住-p_allRecs是指向指针的s指针,而allRecsTemp只是一个指针。

Remember p_allRecs is a pointer to the pointer to the start of the records array: 记住p_allRecs是一个指向记录数组开头的指针:

void AddRecord(struct myRecord **p_allRecs, int p_size){
    int i;
    struct record *allRecsTemp;
    allRecsTemp = (struct record *)malloc((p_size+1)*sizeof(struct record));

    memcpy(allRecsTemp, *p_allRecs, p_size*sizeof(struct_record)); // only if records do not contain pointers to one another!

    free(*p_allRecs);
    *p_allRecs = allRecsTemp;

    (*p_allRecs)[p_size].name = "new record name";
    (*p_allRecs)[p_size].nr = 3; // or whatever

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM