Printing a dynamic array in C -


i'm writing program in c. i'm using dynamic array in program, , using loop cycle through items in array. problem i'm having, when go print list screen (in loop), previous items in list changed created item. don't know what's causing this. have gone through code numerous times in gdb, , still can't find what's wrong.

/* loop, displays weapon list */ (i = 1; < num_places; i++) {     printf("%d. \n",i);     printf("des: %s \n\n",weap_list[i].description); }  /* add function, adds weapon list */ int add_weap(weapon new_weap)  {     if (num_places == num_allocated)      {         if (num_allocated == 0)                 num_allocated = 3;         else              num_allocated *= 2;         void *_tmp = realloc(weap_list, (num_allocated * sizeof(weapon)));         weap_list = (weapon*)_tmp;     }     num_places++;     weap_list[num_places] = new_weap;     return num_places; }  /* code invokes function, adding weapon list */ printf("adding new weapon \n"); weapon temp; printf("please enter description of new weapon. \n"); scanf("%s",weap.description); add_weap(temp);  /* weapon structure */ typedef struct {     char* description; } weapon; 

if point me in right direction, appreciated.

some quick thoughts:

for (i = 1; < num_places; i++) { 

num_places, being array index, start @ 0. loop fail badly 0 or 1 weapons in list. (the condition i < num_places checked after first iteration of loop body. if weap_list has 1 element (at index 0), loop access memory not allocated and not print weapon. start array-handling loops @ 0. times should ever tolerate one-indexed arrays when moving huge amount of fortran code c; when starting scratch, use zero-indexed arrays, k&r intended. :)

   void *_tmp = realloc(weap_list, (num_allocated * sizeof(weapon)));    weap_list = (weapon*)_tmp; 

if _tmp declared (weapon *) tmp = realloc(...), wouldn't need (weapon *) cast on next line.

tiny nitpick: doubling size pretty expensive way go when adding 196609th weapon. consider growing 8 each time. (i'm guessing names you're not going adding 1 item per second weeks on end.)

tiny nitpick: avoid _prefix variable names, reserved c runtime environment. yes, every program uses them, , yes, i've used them, , yes 1 safe :) technically reserved. plain tmp suffice.

larger nitpick: you're not checking return value realloc(3). can fail. application should handle failure gracefully possible.


Comments