Tinkidinki Tinkidinki - 1 month ago 23
C Question

Passing structures into functions in c

I want to write a simple c code to create a garden structure,input details like num_animals, type of garden and size of garden.
However, my code is giving me some garbage output.

#include <stdio.h>
#include <string.h>

struct Garden
{
int num_animals;
int size;
char type[10];
};

void Input(struct Garden gardname)
{
printf("\nEnter number of animals\n");
scanf("%d",&gardname.num_animals);

printf("\nEnter size\n");
scanf("%d",&gardname.size);

printf("\nEnter type\n");
scanf("%s",gardname.type);
}


void Output(struct Garden gardname)
{
printf("Num of animals:%d\n",gardname.num_animals);
printf("size:%d\n",gardname.size);
printf("type:%s\n",gardname.type);
}

int main()
{
struct Garden Lumbini;
Input(Lumbini);
Output(Lumbini);

return 0;
}

Answer

You cannot pass a structure to a function. You must pass a pointer to the structure. The functions you have defined, by default use call by value method of passing arguments, which means that although you have Lumbini structure to which you intend to read and write elements, your functions will instead make a copy of Lumbini, and write to that copy, and not Lumbini

Try this:

#include <stdio.h>
#include <string.h>

struct Garden
{
    int num_animals;
    int size;
    char type[10];
};

void Input(struct Garden *gardname)
{
    printf("\nEnter number of animals\n");
    scanf("%d",(*gardname).num_animals);   

    /*you could also write gardname->num_animals, as mentioned in the comment*/

    printf("\nEnter size\n");
    scanf("%d",gardname->size);

    printf("\nEnter type\n");
    scanf("%s",gardname->type);
}


void Output(struct Garden *gardname)
{
    printf("Num of animals:%d\n",gardname->num_animals);
    printf("size:%d\n",gardname->size);
    printf("type:%s\n",gardname->type);
}

int main()
{
    struct Garden Lumbini;
    Input(&Lumbini);
    Output(&Lumbini);

    return 0;
}
Comments