简体   繁体   中英

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", ...);
}

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.

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM