In: Computer Science
I have a C problem. I need to read the data of a txt file to array by struct, then use these data to sum or sort.
The txt file and the struct like
aa.txt
1 2
3 4
*****************************
struct aaa{
int num1,num2;
}bbb[2];
num1 for 1,3, num2 for 2 4
I made a void readfile () function for read data. How can I pass the numbers to another function ( void sum () and void sort() ) for sum and sort
I finished the void readfile(), but I have no idea how to pass the value to another function.
I tries to use the pointer of struct, can you give me a general idea?
Because I must move data to an array, is my array of struct wrong? I mean if I need to use malloc
Thanks
To pass a struct variable you have to create a pointer and use malloc and pass the pointer to the function and access it using an index.
C++ Code:
#include <stdio.h>
#include <stdlib.h>
//Declaring a struct type
struct aaa{
int num1, num2;
};
//main method
int main()
{
//allocating memory to a struct pointer to store 2 struct variables
of type "aaa"
struct aaa *bbb = malloc(sizeof(struct aaa)*2);
//open the file
FILE *f1;
f1 = fopen("aa.txt", "r");
readFile(f1, bbb); //read the file into the struct
sum(bbb); //calculate sum
sort(bbb); //sort the values
fclose(f1); //close the file
return 0;
}
void readFile(FILE *f1, struct aaa *bbb){
int i=0;
for(i=0; i<2; i++){
//Loop through the file and store in the struct
fscanf(f1, "%d %d",&bbb[i].num1,&bbb[i].num2);
printf("Values are: %d %d\n", bbb[i].num1, bbb[i].num2);
}
}
void sum(struct aaa *bbb){
int i=0;
for(i=0; i<2; i++){
//Calculate sum of each struct variable
printf("Sum of struct %d is %d\n", (i+1),
bbb[i].num1+bbb[i].num2);
}
}
void sort(struct aaa *bbb){
int i=0;
int temp=0;
for(i=0; i<2; i++){
//Sorting the values using a temp variable
if(bbb[i].num2 < bbb[i].num1){
temp = bbb[i].num2;
bbb[i].num2 = bbb[i].num1;
bbb[i].num1 = temp;
}
//Display struct after sorting
printf("After sorting the values are: %d %d\n", bbb[i].num1,
bbb[i].num2);
}
}
Sample Output:
Values are: 1 2
Values are: 3 4
Sum of struct 1 is 3
Sum of struct 2 is 7
After sorting the values are: 1 2
After sorting the values are: 3 4