#include<stdio.h>
struct create
{
int a;
int b;
int c;
float total;
};
struct create Create[3];
float givename(struct create* storage[3]);
int main()
{
for(int j = 0; j<4; ++j)
{
printf("Input a[%d]:", j+1);
scanf("%d", &Create[j].a);
printf("Input b[%d]:", j+1);
scanf("%d", &Create[j].b);
printf("Input c[%d]:", j+1);
scanf("%d", &Create[j].c);
float sum = givename(&Create);
printf("%f", sum);
}
}
float givename(struct create* storage[3])
{
for(int i = 0; i<4; ++i)
{
storage[i]->total = storage[i]->a + storage[i]->b + storage[i]->c;
return storage[i]->total;
}
}
I wanted to take an input into an array of structures and then use it inside a function that has been called by reference.
What am I misunderstanding about the logic?
The function
float givename(struct create* storage[3])
takes an array of pointers to struct create
, you are sending the address of an array of struct create
. If you want an array of pointers to struct create
, do it like this:
struct create * array[3];
array[0] = & Create[0];
array[1] = & Create[1];
array[2] = & Create[2];
Plus, this function stops during the first iteration, because of the return.
Array's size is 3, you're looping 4 times.
Your main
needs a return value;
If you wanted to pass the whole array to givename
(an array of struct create
, not pointers), you don't need to since Create
is global;
For each iteration in the first loop (3 after fixing), you iterate the whole array, I doubt this is what you wanted to do.
The following version prompts to fill 3 struct create
, computes the total for each (and stores it), and prints it.
Is this what you wanted to do ?
#include<stdio.h>
#include <stdlib.h>
struct create
{
int a;
int b;
int c;
float total;
};
struct create Create[3];
float givename(struct create * storage);
int main()
{
for(int j = 0; j < 3; ++j)
{
printf("Input a[%d]:", j+1);
scanf("%d", & Create[j].a);
printf("Input b[%d]:", j+1);
scanf("%d", & Create[j].b);
printf("Input c[%d]:", j+1);
scanf("%d", & Create[j].c);
float sum = givename(& Create[j]);
printf("%f\n", sum);
}
return EXIT_SUCCESS;
}
float givename(struct create * storage)
{
storage->total = storage->a + storage->b + storage->c;
return storage->total;
}
echo 1 2 3 4 5 6 7 8 9 | yourProgram
>> Input a[1]:Input b[1]:Input c[1]:6.000000
>> Input a[2]:Input b[2]:Input c[2]:15.000000
>> Input a[3]:Input b[3]:Input c[3]:24.000000
What you wanted to achieve is quite unclear, and the naming doesn't help, I recommend you to give better names:
struct create
doesn't describe what is stored insideConsider compiling with -Wall -Wextra -Werror.