WLL
WLL

Reputation: 1

Pass struct to function C

Firstly, I am new to C programming and I wanted to know how can I pass a struct through a function?

For example :

typedef struct
{
 char name[20];
}info;

void message()
{
 info n;

 printf("Enter your name : ");
 scanf("%s", &n.name);
}

And I want to pass the entered name into this function so that it will print out the name.

void name()
{
printf("Good morning %s", ...);
}

Upvotes: 0

Views: 110

Answers (3)

Irshad
Irshad

Reputation: 13

Create the function definition that takes 'info' (struct) as a parameter:

void name (info);

Define the function as:

void name(info p) {
    printf("Good morning %s", p.name);
}

Then call the function appropriately:

name(n);

Upvotes: 1

Tor Klingberg
Tor Klingberg

Reputation: 5098

Well, if you just want to print the name you can pass in a pointer to the string itself.

void name(char *str)
{
  printf("Good morning %s", str);
}

Called as name(n.name);

But let's assume this is a simplified example and you really want access to the whole struct inside the function. Normally you would pass in a pointer to the struct.

void name(info *ptr)
{
  printf("Good morning %s", ptr->name);
}

Called as name(&n);

Instead of using a pointer, you can pass in the whole struct by value, but this is not common as it makes a temporary copy of the whole struct.

void name(info inf)
{
  printf("Good morning %s", inf.name);
}

Called as name(n);

Upvotes: 0

Peter - Reinstate Monica
Peter - Reinstate Monica

Reputation: 16112

Yes, you can simply pass a struct by value. That will create a copy of the data:

void name(info inf)
{
   printf("Good morning %s", inf.name);
}

Creating a struct whose only member is an array (as you did) is a known method to "pass arrays by value" (which is not normally possible).

For large structs it is common to just pass a pointer:

void name(info *inf)
{
   printf("Good morning %s", inf->name);
}

But changes to the pointer's target will then be visible to the caller.

Upvotes: 3

Related Questions