I have this struct i created called User which stores all kind of data, now i'm trying to create an array of it (User*) and get data from a file, this is what i do in the start of my main program:
int amount = 0;
User* users = NULL;
// read from file functions
loadUsers(&users,&amount);
And the function (the amount of users is the first line of my txt file):
void loadUsers(User** users,int* amount2){
int amount, i = 0, j;
char temp[STRING_SIZE], temp2[STRING_SIZE];
FILE* f;
f = fopen("input.txt", "r");
if (!f){
return;
}
if (fileEmpty(f)){
return;
}
fscanf(f, "%d", &amount);
*amount2 = amount;
*users = malloc(sizeof(User)*amount);
/**users = (User*)malloc(sizeof(User)*amount);*/
while (!feof(f)){
fscanf(f, "%s", temp);
users[i]->ID = (char*)malloc(sizeof(char)*(strlen(temp) + 1));
strcpy(users[i]->ID, temp);
fscanf(f, "%s", temp);
users[i]->f_name = (char*)malloc(sizeof(char)*(strlen(temp) + 1));
strcpy(users[i]->f_name, temp);
fscanf(f, "%s", temp);
users[i]->l_name = (char*)malloc(sizeof(char)*(strlen(temp) + 1));
strcpy(users[i]->l_name, temp);
i++;
}
For some reason i get an error and while debugging i see the allocation is wrong since i only have users[0] and not users[1], like an array of users should have, even when the amount is higher than 1.
My target is to have an array, which each cell of it is a User.
What could be the reason?
Edit: User struct:
struct User{
char* ID;
char* f_name;
char* l_name;
int age;
char gender;
char* username;
char* password;
char* description;
char** hobbies;
}typedef User;
users[0]?Userstructchar id[100]; f_name[100]; l_name[100]; while ((i < amount) && (fscanf(f, "%99s%99s%99s", id, f_name, l_name) == 3)) { /* copy the strings to users[i] here */ };.amount. Trying printing the value ofamountafter you read it to see what value you get.