c - Trouble storing a struct in an array -
i want create database sort of, stores list of 5000 names , 5000 coresponding salaries array, can't find problem since console either crashes or compiler gives me following error: "cannot convert 'char* ()[30]' 'char' argument '1' 'char*' fgets(char*,int,*file)".
edit: changed whatever figure out in code, , seem have issue line in particular:
person* tab = calloc(n, sizeof(struct));
i can't spot other errors(lack of experience), , don't know use instead of fgets put in line.
#include <stdio.h> #include <stdlib.h> #define n 5000 typedef struct { char name[30] int salary; } person; int main() { person* tab = calloc(n, sizeof(struct)); file * input; input = fopen("in.txt","r+"); int nr=0; int r; while(nr<5000) { fscanf(input,"%s",tab[nr].name); fscanf(input,"%d",tab[nr].salary); nr++; } printf("%s %d",tab[1].name,tab[1].salary); fclose(input); return 0; }
you should avoid putting data on stack, normal variable do. occupy around 5000 * (30 + 4 * 5000) = 95 mb of stack space, might more operating system feels reasonable.
anyway, fix not allocate on heap; fix change declaration. believe there's logic error, since allocate space 5000 salaries per person, not meant.
also, name
field should array of characters, you've declared array of character pointers, warnings about.
i believe should have:
struct person { char name[30]; int salary; };
this drop memory usage struct person tab[n];
down around 5000 * (30 + 4) or around 166 kb way more reasonable. assumes 4-byte int
pretty common situation.
finally, file reading code not nicely designed, not work.
look using fgets()
read lines, stopping when fails (i.e. never calling feof()
), , parsing/tokenizing each line read. remember names can contain whitespace, make %s
in sscanf()
stop.
Comments
Post a Comment