#include<stdio.h>
struct mystruct{
int age; //age of child
int flag; //flag: if 1 then change the age, if 0 then don't
};
///////////////////////////////////////////////////////////////////////////////
void Change_Age_Of_First_Child(struct mystruct *child[]){ //parameter is a structure passed by reference
if (child[0]->flag==1){ //checking if flag of first child is 1
child[0]->age=0; //if it is 1 then change the age to 0
}
}
///////////////////////////////////////////////////////////////////////////////
int main(){
int x,i; //x is used to store the integer version of ch, i is loop counter
char ch; //used to store character from file
FILE *test;
test=fopen("test.txt","r+");
struct mystruct child[7];
for(i=0;i<7;i++){
ch=fgetc(test); //this ch is the age
x= ch - '0'; //saving integer version of ch
child[i].age=x; //saving x into age part of structure
ch=fgetc(test); //this ch is the flag
x= ch - '0'; //saving integer version of ch
child[i].flag=x; //saving x into flag part of structure
fseek(test,2,SEEK_CUR); //moving to next line of file for the consecutive loops
}
Change_Age_Of_First_Child(&child);
fclose(test);
printf("%d",child[0].age);
}
File "test.txt":
51
81
90
90
70
51
80
I am trying to learn passing structures by reference. I made a simple test program to read the age and flag from a file and store it into the array called child which is a structure. Then I pass child as reference into a function. In that function, to make things simpler, I only check the first element of child (which contains data for the first line of file). If the flag is 1 then the set the age to 0.
However when I print the age of the first child in the main program it doesn't work. In fact, the console shows me nothing. It runs for a while then simply says "process exited" which means that the program is finished. Help would be appreciated.
Note: the first character of every line of file is the age and second is the flag.