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.

  • Just a question - why these movements with calloc , copying back and forth? realloc much nicer. Even if calloc - well, make a new array, write it into it, and then just assign a pointer to it names , 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
  • @Harry: This pattern is found with some kind of unnatural repeatability. I suspect that somewhere there is a kind of “textbook” walking around in which this strange manner is imposed when re-allocating memory to drive data through a completely unnecessary intermediate array. - AnT
  • Thank you, but for some reason the data in the structure is not saved correctly. Only the last line is saved correctly, the other previous lines are shifted and not fully displayed. - Asukira
  • In reallock made a mistake, corrected. Now only the last line is displayed, all other lines are zero when displayed are zeros. - Asukira

1 answer 1

I have a theory. I think the problem is not in the function itself (it can be written better, but this is a separate question), but in its use. I do not know for sure (therefore, this is only a theory), but I suspect that you call it something like this:

 struct name *names = NULL; int count_names = 0; new_record(names, &count_names); new_record(names, &count_names); new_record(names, &count_names); 

while your implementation involves:

 struct name *names = NULL; int count_names = 0; names = new_record(names, &count_names); names = new_record(names, &count_names); names = new_record(names, &count_names); 

Maybe I'm not at all right, but this explains the strange behavior you are talking about.