简体   繁体   English

将struct传递给函数C

[英]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? 首先,我是C编程的新手,我想知道如何通过函数传递struct

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: 创建以“ info”(结构)为参数的函数定义:

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); 叫作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); 称为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); 称为name(n);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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