Reputation: 83
I am trying to print few arrays which are calculated in one separate function and print in another separate function than that function is called in the main
function.
This is the first function that stores and calculates values from struct varOne
void function1(struct varOne arrayOne[], struct varTwo* finalMark) {
int i;
for (i=0;i<12;i++) {
finalMark->num1 = arrayOne[i].mark1 + arrayOne[i].mark2;
finalMark->num2 = arrayOne[i].mark3 + arrayOne[i].mark4;
}
}
This function prints out the total:
void function2(int totalNumber, struct varTwo* finalMark) {
printf("%d, %d \n", finalMark->num1, finalMark->num2);
}
We then print out function2 in the main like this:
for(i=0;i<6;i++){
function2(i+1,&finalMark[i]);
}
The problem is the program print one specific value 6 times, something like this:
45, 34
45, 34
45, 34
......
But it should print 6 different values because in function1
we are storing result from all arrays!
Upvotes: 0
Views: 62
Reputation: 16607
for (i=0;i<12;i++) {
finalMark->num1 = arrayOne[i].mark1 + arrayOne[i].mark2;
finalMark->num2 = arrayOne[i].mark3 + arrayOne[i].mark4;
}
In function1
these two variables num1
and num2
gets recent value in every iteration and previous value is lost . And they contain last value stored in them . And therefore , when you print it prints all the same values.
You can write the above like this -
for (i=0;i<12;i++) {
finalMark[i].num1 = arrayOne[i].mark1 + arrayOne[i].mark2;
finalMark[i].num2 = arrayOne[i].mark3 + arrayOne[i].mark4;
}
Note - Just make sure you allocated your struct pointer sufficient memory .
Upvotes: 2