I’m a beginning at C and I’m quite confused and clueless on how to store input into an array when that input was made by calling a function for.
I have an inputCustomerDetails function and I don’t quite know how to store what it reads into an array.
typedef struct customer
{
char name[256];
int age;
}Customer
Customer inputCustomerDetails()
{
Customer new_cust;
printf("Enter your name: ");
scanf("%s", new_cust.name);
printf("Enter your age: ");
scanf("%s", new_cust.age);
return new_cust;
}
void main(){
Customer customer[5];
Customer *cust;
cust = customer;
*cust = inputCustomerDetails();
for(int i = 0; i < 5; i++)
{
scanf("%d", &cust[i]);
}
}
I think the scanf part is obviously wrong but I was basically doing trials and error by reading about arrays.
>Solution :
Your code is full of bugs and misconceptions.
This is what you want:
#include <stdio.h>
#include <stdlib.h>
typedef struct customer
{
char name[256];
int age;
} Customer; // a ; was missing here
Customer inputCustomerDetails()
{
Customer new_cust;
printf("Enter your name: ");
scanf("%s", new_cust.name);
printf("Enter your age: ");
scanf("%d", &new_cust.age); // a & was missing here, and %s
// wa used wrongly rather then %d
return new_cust;
}
void main() {
Customer customer[5];
for (int i = 0; i < 5; i++)
{
customer[i] = inputCustomerDetails();
}
// now the customer array contains 5 customers
}
The main function was overly complicated and wrong.