简体   繁体   English

将结构作为参数传递

[英]Passing a struct as an argument

I have been trying to pass a struct as an argument, but I seem to have an issue with the different structs. 我一直试图通过一个结构作为参数,但是我似乎对不同的结构有疑问。 My goal is to create a generic function that takes a struct and then overwrites a field in particular struct. 我的目标是创建一个接受结构的通用函数,然后覆盖特定结构中的字段。

struct information{
        int number;
 };
typedef struct information Jack;
typedef struct information Joe;

and then a function. 然后是一个功能。

foo(struct information Name , int randomNumber) {
     Name.number = randomNumber;
}

However, when I print Jack.number and Joe.number, it prints 0. 但是,当我打印Jack.number和Joe.number时,它打印0。

void main() {
    int h =5;
    foo(Joe,h);
    foo(Jack,h);
    printf("%d",Jack.number);
    printf("%d",Joe.number);
  }

Is there any way of solving this issue and create such a generic function? 有什么方法可以解决这个问题并创建这样的泛型函数吗?

Perhaps you should pass a pointer to your struct, like this: 也许您应该将指针传递给您的结构,如下所示:

foo(struct information *Name , int randomNumber) {
     Name->number = randomNumber;
}

You would call your function like this: 您将这样调用函数:

foo (&Jack, 42);

[Edit] Oh, and there's something wrong with your declarations as well. [编辑]哦,您的声明也有问题。 Maybe you could declare your objects like this: 也许可以这样声明对象:

typedef struct informationStruct {
        int number;
} Information;

Information Jack;
Information Joe;

and your function like this: 和你的功能是这样的:

foo(Information *Name , int randomNumber) {
     Name->number = randomNumber;
}

C passes structs by value (as every other argument type). C按值传递结构(与其他所有参数类型一样)。 If you want to see changes outside of the function, pass it by reference: 如果要查看功能之外的更改,请通过引用传递它:

void foo(struct information *name, int randomNumber) {
    name->number = randomNumber;
}

foo(&joe, 42);

You are passing the struct by value. 您正在按值传递struct Whatever changes you make to Name in foo affects only the copy of the object in foo . foo Name所做的任何更改都只会影响foo对象的副本。 It does not change the value of the object in the calling function. 它不会更改调用函数中对象的值。

If you want the change to take effect in the calling function, you'll need to pass a pointer to it. 如果您希望更改在调用函数中生效,则需要向其传递一个指针。 For that, you'll need to change the interface of foo . 为此,您需要更改foo的接口。

foo(struct information* Name , int randomNumber) {
     Name->number = randomNumber;
}

You'll need to change the call also to match the interface. 您还需要更改呼叫以匹配接口。

foo(&Joe,h);
foo(&Jack,h);

Remember that C passes, values to function and not reference. 请记住,C通过了,值起作用了,而不是引用了。 So as everyone has mentioned,you could pass the address of the structure(which you want to modify) to the function and then the changes made to the structure inside that function would be automatically reflected in main function. 因此,正如每个人都提到的那样,您可以将结构(要修改)的地址传递给函数,然后对该函数内部的结构所做的更改将自动反映在主函数中。

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

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