passing a struct to a function and loop through it - c

Trying to pass a struct to a function and browse through it. Is this the correct way to pass a struct to a function? The for loop in the function view() doesn't seem to work. Any help with that too would be appreciated.
My structs:
typedef struct {
char name[20];
employee *list_employees;
int empl_count;
} agency;
typedef struct {
char name[30];
int age;
} employee;
Important pars of the code:
int main()
{
//...
int nmbr_agencies;
agency *list_agencies = malloc(sizeof(agency) * nmbr_agencies);
view(&list_agencies, &nmbr_agencies);
}
void view(agence *ListA[], int *nmbr)
{
int i=0;
for (i = 0; i < *nmbr; i++){
printf("name of agency: %s\n", ListeA[i]->name);
printf("number of employees\n, ListeA[i]->empl_count);
}
}

No.
You should just pass a single array if that is what you have, not pretend (in the call) that you have an array of pointers which you don't have.
Make the function:
void view(const agency *list, size_t number);
and call it like so:
view(list_agencies, nmbr_agencies);
Then inside the function, do direct accesses:
printf("name of agency: %s\n", list[i].name);
since you don't have an array of pointers.

Related

How can I increment the value in the called function?

How can I pass the pointer to the structure to another function?
sample:
#include<stdio.h>
struct customer{
char name[50];
int number;
};
void input(){
struct customer details;
printf("enter your name: ");
scanf("%s",details.name);
details.number++;
printf("%d\t%s",details.number,details.name);
}
int main(){
struct customer details;
input();
//pcust->number++; how should I declare this?
printf("%d\t%s",details.number,details.name);
}
how do you automatically assign a number in a struct where I can call its value in other functions?
suppose I have this struct
struct customer{
char name[50];
int number;
};
and request input for the user
void input(){
struct customer details;
printf("enter your name");
scanf("%s",details.name);
printf("enter your number");
scanf("%d",&details.number);
}
instead of asking them to enter their number in the function to call it by value, how can I assign it automatically, so I can call it by its value? The possible output I need is like this so that in the next function again, I can call by its value again.
1 customer1
2 customer2
....
#include <stdio.h>
struct customer
{
char name[50];
int number;
};
void input(struct customer *pDetails)
{
printf("enter your name: ");
scanf("%s", pDetails->name);
pDetails->number++;
printf("%d\t%s \n", pDetails->number, pDetails->name);
}
int main()
{
struct customer details = {};
input(&details);
printf("%d\t%s \n", details.number, details.name);
}
Your main problem is that you do not use any function parameters.
You need to have some kind of search (for example if you want to modify a customer record
Use arrays to store multiple data.
Example:
struct customer
{
char name[50];
int somedata;
};
struct database
{
size_t size;
struct customer customers[];
};
struct customer *findCustomer(const struct database *db, const char *name)
{
struct customer *result = NULL;
if(db)
{
for(size_t i = 0; i < db -> size; i++)
if(!strcmp(db -> customers[i].name, name))
{
result = (struct customer *)&db -> customers[i];
break;
}
}
return result;
}
struct database *addCustomer(struct database *db, const char *name)
{
size_t newSize = db ? db -> size + 1 : 1;
db = realloc(db, newSize * sizeof(db -> customers[0]) + sizeof(*db));
if(db)
{
strcpy(db -> customers[db -> size].name, name);
}
return db;
}

Passing array of struct to a function

I'm trying to pass data of a struct between the main and another function (on a different file .c) with no success. I have a struct like this
struct player{
char name[10];
int budget;
};
typedef struct player Player;
void PrintFunc(Player p); //function prototype
Player gamer[2] = {{"Alice", 100},
{"Bob", 100 }};
And I call it from the main func with something like
PrintFunc(gamer);
The function structure should be something like this
void PrintFunc(Player p){
//stuff
}
What am I doing wrong?
gamer is an array, PrintFunc expects a single object.
Option 1:
PrintFunc(gamer[0]);
PrintFunc(gamer[1]);
Option 2: change the function to accept a pointer to Player objects:
void PrintFunc(Player *p, size_t len){
for(size_t i = 0; i < len; ++i)
// do something with p[i]
}
int main(void)
{
Player gamer[2] = {{"Alice", 100},
{"Bob", 100 }};
PrintFunc(gamer, sizeof gamer / sizeof *gamer);
return 0;
}
void PrintFunc(Player p[]){
//stuff
}
Receive array of player objects when sending array of player objects

C program football team structure with pointer elements and dynamic allocation

I have a question about passing function to another function which both have structure as arguments. First I created two structures:
typedef struct
{
char name[25],surname[25];int number;
}PLAYER;
typedef struct
{
char nameofteam[25];int numberofplayers;char *players;
}TEAM;
Then I defined a function to read elements of one player:
void readplayer(PLAYER *);
void readplayer(PLAYER *pi)
{
printf("name:");scanf("%s",pi->name);
printf("surname:");scanf("%s",pi->surname);
printf("number of player:");scanf("%d",&pi->number);
}
My question is how to create function which prototype is void readteam(TEAM*) which will read data for one team, but using function readplayer and call it in main()? Here is what I have tried:
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
char name[25],surname[25];int number;
}PLAYER;
typedef struct
{
char nameofteam[25];int numberofplayers;char *players;
}TEAM;
void readplayer(PLAYER *pi)
{
printf("name:");scanf("%s",pi->name);
printf("surname:");scanf("%s",pi->surname);
printf("number of player:");scanf("%d",&pi->number);
}
void readteam(TEAM *pt)
{
char players[101];int i;
printf("name of team:");scanf("%s",pt->nameofteam);
printf("number of players in team:");scanf("%d",&pt->numberofplayers);
printf("players:");scanf("%s",players);
pt->players=(char *)calloc(length(players)+1,sizeof(char));
copy(pt->players,players);
for(i=0;i<pt->numberofplayers;i++)
{
printf("%d.",i+1);
readplayer(pt+i);
}
}
void erase(TEAM *);
void erase(TEAM *pt)
{
free(pt->players);
}
int length(char *s)
{
int d=-1;
while(s[++d]);
return d;
}
void copy(char *s1,char *s2)
{
while(*s1++ = *s2++);
}
int main()
{
int i,n;
TEAM *p;
do
{
printf("n=");scanf("%d",&n);
}
while(n<1);
p=(TEAM *)malloc(n * sizeof(TEAM));
for(i=0;i<n;i++)
{
printf("%d.",i+1);readteam(p+i);
}
free(p);
}
This gives me an error at the last input (in compiling, not debugging). Must be because of inappropriate use of dynamic allocation. I didn't use <string.h library. Obviously, only the readteam function has to be in main().
Thanks for the answers.
You are confused on how to store the playsrs. You have created a PLAYER struct, but you never use it. Instead, you insist that players must be a single string.
But it should work like this: You have n teams. Ecah team has m players. All team info is stored in your ´TEAMstruct. All player info is stored in yourPLAYERstruct. Because a team is made up of players, there should be aPLAYER` entry in your struct:
typedef struct {
char name[25];
char surname[25];
int number;
} PLAYER;
typedef struct {
char nameofteam[25];
int numberofplayers;
PLAYER *players;
} TEAM;
Then, when you read players, you read the bare team info in readteam. But you don't read anything about individual players there, because you delegate that to readplayer. Of course, the pointer you pass to that function must be that for a player, not one for a team:
void readplayer(PLAYER * pi)
{
printf("name:");
scanf("%s", pi->name);
printf("surname:");
scanf("%s", pi->surname);
printf("number of player:");
scanf("%d", &pi->number);
}
void readteam(TEAM * pt)
{
int i;
printf("name of team:");
scanf("%s", pt->nameofteam);
printf("number of players in team:");
scanf("%d", &pt->numberofplayers);
pt->players = calloc(pt->numberofplayers, sizeof(*pt->players));
for (i = 0; i < pt->numberofplayers; i++) {
printf("Player %d:\n", i + 1);
readplayer(pt->players + i);
}
}
Your cast to (char *) hides the warning about incompatible types. You should cast only when you know what you're doing. In this simple program, you don't need casts.
In your original code, there are warnings about "implicit declarations". These concern your copy and length functions. (By the way, what's wrong with strlen and strcpy?) You should move these functions to the top so that they are declared before they are called. ALternatively, provide prototypes at the beginning of your code or in a header file, which you #include at the top. (But now that you read into PLAYER structs, these functions are no longer needed.)

How to parse a structure array as a parameter?

How should I parse an array of structures as parameter to a function?
For example, I have the following structure definition:
struct Town
{
char *TownName;
char **GiftList;
int *GiftCount;
int GiftTypes;
};
and a declaration of an array of such structures, in my main:
struct Town TownList[100];
struct Town AuxiliaryStructure;
I have written a custom sorting function for this array, in which I want to make use of each structure's fields, but I do not know how to provide the array TownList[100] to the sort function.
To pass an array of anything to a function, you can just pass a pointer to the first element plus an array length:
struct mystruct {
char* something;
/* ... */
}
struct mystruct myarray[100];
void do_something(struct mystruct* array, int length)
{
int i;
for (i=0; i<length; ++i)
{
array[i].something = ...
}
}
int main(void)
{
do_something(myarray, 100);
return 0;
}
Based on what you wrote, you would reference it in the caller and pass the result. For example:
void sort(char* str){
...
}
int main(){
for(int i=0; i<100; ++i){
sort(array[i].something);
}
}
Alternately you may want to pass the full array and handle it in another function, which would be like this:
void sort(struct mystruct * array){
...
}
int main(){
for(int i=0; i<100; ++i){
sort(array);
}
}
If, on the other hand, you meant that you want to sort the outer array of structures by the contents of something, then you would either have to pass the array as above and implement your own sort, or use a sorting function that takes a function pointer so you can write a comparator. The latter is available in the standard C library, and could be used something like this.
#include <stdlib.h>
int compare_mystruct_by_something(const void *a, const void *b){
return strcmp(((struct mystruct*)a)->something, ((struct mystruct *)b)->something);
}
int main(){
qsort(array, 100, sizeof(struct mystruct), compare_mystruct_by_something);
}

creating, passing, getting back Array of a Struct and loop throuh it in C

I need to execute a function that returns array of a specified struct with variable length. Then I should loop through the returned array.
example struct :
typedef struct student {
int id;
char *name;
int grade;
} Student;
function prototypes 1 :
Student *students;
students = findStudentByGrade(int grade);
function prototypes 2 :
Student *students;
int retval = findStudentByGrade(&students, int grade);
I am bit confused on above methods. How can correctly define a array of struct? call function ? and loop through it untill end? Can some one help me please.
You can do this in this way. This code is working. I tested in CodeLite.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct student {
int id;
char *name;
} Student;
Student *findStudent(int *asize, const int grade);
int main(void)
{
Student *stds;
int asize = 0;
stds = findStudent(&asize, 5);
int i;
for (i = 0; i < asize; i++) {
printf("ID : %i\n", stds[i].id);
}
return 0;
}
Student *findStudent(int *asize, const int grade)
{
struct student *stds = malloc(sizeof(struct student) * 3);
stds[0].id = 10;
stds[1].id = 20;
stds[2].id = 40;
*asize = 3;
return stds;
}
Get the array of struc as returned statement and pass an int variable with argument list to get the size back and simply loop through using a for loop. Or else you will find problem in looping. It is more easy to get the array size from the function which create the array.
I mean this is quite a basic question, but:
Defining array of your structures would look like:
int size = ...;
Student *students = (Student*) malloc(sizeof(Student) * size);
Then just pass that to the function (both size and the array) and then just loop until i < size.
Ofcourse, don't forget to:
free(students);
at the end.

Resources