'an fscanf() somehow cancels variables in a struct
i recently started doing an exercise where I had to write numbers in an array of structs.
The problem I faced was that when I used fscanf() at the end of the code, the variables in the node array were being deleted.
I don't know if it's a memory problem, because I'm still a noob in C.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *f = fopen("grafo.txt" , "r");
char tempRead[1] = "~";
int endReadFlag = 0;
int nodeCounter = 0;
char alph[12] = "abcdefghijk";
// if the file cant open
if (f == NULL){
printf("Errore");
exit(1);
}
// Counting nodes
while(endReadFlag == 0){
fscanf(f, "%s" , &tempRead);
if (strcmp(tempRead, ";") == 0){
nodeCounter++;
} else if (strcmp(tempRead, ".") == 0){
tempRead[0] = "z";
endReadFlag = 1;
}
}
endReadFlag = 0; // resetting flag
// Creating node structure
struct Nodo{
char name;
char adiacenze[nodeCounter][1];
};
struct Nodo nodi[nodeCounter];
// Creating structs
for(int i = 0 ; i < nodeCounter ; i++){
nodi[i].name = alph[i];
//printf("%c" , nodi[i].name);
}
rewind(f); // rewindin the file
// Setting chains in the struct array
for(int i = 0 ; i < nodeCounter ; i++){
for(int j = 0 ; j < nodeCounter + 2; j++){
fscanf(f , "%s", &tempRead);
printf("%c" , nodi[i].name);
}
}
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
