got a question how to save a struct to an array and print it out in main()
.
My idea is, to get data of a .txt and then save it in a struct array. If i output it directly with printf()
it works fine.
But if I want to save it in a struct array and print it out at the
main() I get trash values, nothing or just the last read struct will be saved to all positions of the array.
My code looks like this:
typedef struct CAR {
char* nickname;
char* model;
} CAR;
void getInputFromFile(struct CAR *arr) {
. . .
. . .
char *nickname = malloc(...);
char *model = malloc(...);
int i=0;
while(fscanf(file,"%s %s\n", model, nickname)==2){
printf("%s %s\n", model, nickname); // this works fine!!!
// Now when i try to save it in a struct it doesn't work
arr[i]->model = model;
arr[i]->nickname = nickname;
i++;
}
free(nickname);
free(model);
}
int main (){
struct CAR* arr[size];
getInput(arr);
// Now iterate over arr to look at values
for(i = 0; i < size; i++){
...
}
}
File input format looks like this:
nickname model\n
nickname model\n
...
Thanks for all your help in advance!