I am trying to access all values that I call. I'm not sure if I use array values correctly. In code below I'm trying to write values in file to memory and then call them by address. what is the problem? Am I overwriting on same memory adresses or I call them wrongly? Any help please?
my text file:
0 0 100 500 player1
0 1 400 450 player2
1 1 300 600 player3
FILE *fp;
struct ob {
int x;
int y;
int c_hp;
int max_hp;
char name[100];
int p_id;
};
struct ob *ptr;
int count = 0;
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: program <File name>\n");
exit(1);
}
read_player_values();
}
void read_player_values() {
ptr = (struct ob *)malloc(sizeof(struct ob));
if (ptr == NULL)
printf("out of memory");
else {
while (!feof(fp)) {
count++;
fscanf(fp, "%d%d%d%d%s", &ptr->x, &ptr->y, &ptr->c_hp, &ptr->max_hp,
ptr->name, &ptr->p_id);
ptr->p_id = count;
printf("%d %d %d %d %s %d", ptr->x, ptr->y, ptr->c_hp, ptr->max_hp,
ptr->name, ptr->p_id);
printf("\n");
}
fclose(fp);
printf("------\n");
for (int i = 0; i < count; i++) {
/* here is my problem */
/*trying to print all player names here*/
printf("%s\n", (ptr - i)->name);
}
}
}
fp? Inmainyou check whether filename was passed, but don't use it.ptris not a pointer to anobarray but a pointer to a singleobstruct, but you seem to assume that its an array with the printing part. You just rewriting this singleobelement with every loop iteration and not building an array as you might want.read_player_values()method after that and assingfpinfscanf. I'm reading file values and assing them to struct variablescount++you can do something likeptr = realloc(ptr, count * sizeof(struct ob));and useptrlike&ptr[count-1].xin every place.