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
Related
I apologise if this seems simple, I'm still learning and I'm new to C.
I have this as my struct:
struct Game{
char id;
char name[50];
char genre[20];
char platform[15];
char company[30];
float price;
int quantity = 10;
};
And this declared as a struct array:
struct Game gList[30];
I have a function where I'm passing all of 'gList' to search through values in the gList[i].name variables.
So my question is, is it possible to send only the gList[i].name part of the struct to the function as a parameter?(ie All the 30 name values only).
No.
But you could make an array of pointers that point to the name field and pass it to the function:
char* ptr[30];
for(int i = 0; i < 30; i++)
ptr[i] = gList[i].name;
func(ptr);
No you can't. However, you can pass iterators to functions just fine. Typical pattern:
struct context { struct Game *gList; int nList; int i; }
char *iter_names(void *baton)
{
struct context *ptr = baton;
if (ptr->i == ptr->nList) return NULL;
return ptr->gList[ptr->i++].name;
}
void wants_name_array(char (*nextname)(void *), void *baton)
{
while (char *name = nextname(baton))
{
printf("%s\n", name);
/* and whatever else you are doing */
}
}
/* ... */
struct context baton = { gList, 30, 0 };
wants_name_array(iter_names, baton);
Yeah it looks kinda bad. Thankfully, gcc has an extension that makes this much better.
void wants_name_array(char (*nextname)())
{
while (char *name = nextname())
{
printf("%s\n", name);
/* and whatever else you are doing */
}
}
/* ... */
{
int i = 0;
char *nextname()
{
if (i == 30) return NULL;
return gList[i++].name;
}
wants_name_array(nextname);
}
When using this particular gcc extension, never ever return nested functions. Undefined behavior.
I'm trying to print out all the members of each structure from a list. I was provided the print functions below to print out an element from a generic list.
Here is the structure definition of my list, which is in a generic list ADT c file:
struct list_type {
void *data;
int size;
int capacity;
int elementSize;
int (*comparePtr) (void *d1, void *d2);
};
So in a generic list ADT c file, I have this print function:
// client needs to send a pointer to a function capable of printing an element
void printl(ListType listptr, void (*printItem) (void *d)) {
int i;
for(i = 0; i < listptr->size; i++) {
// since we cannot use data[i], we need to calculate the address
// of the element to be sent to the client's print function
// since data is of type void, the formula is:
// the beginning address of the array + (offset x element size)
printItem(listptr->data + i * (listptr->elementSize) );
printf(" ");
}
printf("\n");
}
I call my printl function like so:
printl(clientList, printItem);
In my driver file, there's a function to print out an element from the list:
void printItem (int* p) {
printf("%d", *p);
//`my attempt at printing the members of an individual structure from the list
// printf("%s", ((Client *)&p)[0]);
}
Here is my Client structure definition:
struct client_tag {
char id[5];
char name[30];
char email[30];
char phoneNum[15];
};
When I run the program, I get a bunch of weird characters. How do I fix this?
Assuming you left out the line
typedef struct client_tag Client;
and assuming the strings of Client are guaranteed to be null terminated, this is the idea:
void printItem (const Client* p) {
printf("%s\n", p->id);
}
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);
}
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.
#include <stdio.h>
struct player{
int life;
};struct player info;
void name(struct player *info);
int main(void)
{
info.life = 20;
name(&info);
printf(">>>>%d", info.life);
return 0;
}
void name(struct player *info)
{
info.life = 20
}
Hi, well this is just a practice code I am trying to pass a struct to a function by reference, but how do I change the value of the int in the struct? when i try to compile
info.life = 20; I get an error, what am i doing wrong? I also tried doing
*info.life = 20; but I also got an error. Thanks you guys! :)
Here:
void name(struct player *info)
{
info.life = 20;
}
that should be info->life. because info is a pointer.
I usually typedef my structs to make it more readable.
typedef struct _Player
{
int life;
} Player;
Then to access your struct or pass it in you would do:
void name(Player *pInfo)
{
pInfo->life = 20;
}
I also prepend a p for any pointer variable, so that you can easily see when you have a pointer or not.