views:

348

answers:

2

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;
+2  A: 

In C, structs can be assigned. You can therefore say things like:

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

No need for calls to strcpy() etc. Doing this should simplify your code. 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.

anon
Ok, great thanks!
Chris_45
A: 

Remember p_allRecs is a pointer to the pointer to the start of the records array:

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

}
Autopulated