When outputting a structure after adding, for some reason, only the last entry is correctly displayed. For the reason unknown to me, the remaining blocks are filled with either zeros or incomprehensible characters.
struct name* new_record(struct name *names, int *count_names) { *count_names += 1; if ( names == NULL) { fprintf(stdout,"\nThe structure is empty\n"); names = (struct name*)calloc(1,sizeof(struct name)); } fprintf(stdout,"count_names = %d\n", *count_names); struct name new_name; printf("Enter the new data\n"); printf("Enter the first name\n"); fgets(new_name.first_name, MAX_NAME,stdin); new_name.first_name[strlen(new_name.first_name) - 1] = '\0'; printf("Enter the last name\n"); fgets(new_name.last_name, MAX_NAME,stdin); new_name.last_name[strlen(new_name.last_name) - 1] = '\0'; printf("Enter the score:\n "); scanf("%d", &new_name.score); names = realloc(names,*count_names*sizeof(struct name)); names[*count_names-1] = new_name; printf("\nData added\n\n"); int i; for(i = 0; i < *count_names; ++i) { fprintf(stdout,"%s\t%s\t%d\n",names[i].first_name,names[i].last_name, names[i].score); } return names; } Please help in resolving this issue.
calloc, copying back and forth?reallocmuch nicer. Even ifcalloc- well, make a new array, write it into it, and then just assign a pointer to itnames, first freeing the old array. Why write to a temporary array, then, without releasing the old one (leak!) Again allocate memory for the array, copy again ... Extra work. - Harry