简体   繁体   English

传递结构项作为参数

[英]Passing a struct item as the parameter

I understand it is possible to pass a struct as an argument etc. 我知道可以将结构作为参数传递。

But is it possible to have the parameter preset so only a specific struct item can be passed such: 但是是否可以预先设置参数,以便只能传递特定的结构项,例如:

struct inventory* searchForItem(struct stockItem.componentType code){

I'm getting : error: expected ';' 我得到:错误:预期为';' , ', ' before token ,','在令牌之前

EDIT: 编辑:

typedef struct stockItem {
    char *componentType;
    char *stockCode;
    int numOfItems;
    int price;
} stockItem;

The type of that component is char * , so just make that the type of the parameter. 该组件的类型为char * ,因此只需使该参数为类型即可。

struct inventory* searchForItem(char *code){

If you want to make the type more strict, make a typedef for the field in question: 如果要使类型更严格,请为相关字段创建一个typedef:

typedef char * stockItem_componentType;

typedef struct stockItem {
    stockItem_componentType componentType;
    char *stockCode;
    int numOfItems;
    int price;
} stockItem;

struct inventory* searchForItem(stockItem_componentType code){

Note that this hides a pointer behind a typedef which is not recommended. 请注意,这会将指针隐藏在typedef后面,这是不推荐的。 Then people reading your code (including yourself) won't know just by looking at it that it's a pointer, which can lead to confusion. 这样一来,阅读您的代码(包括您自己)的人们就不会仅仅通过查看它的指针就知道它是一个指针,这可能导致混乱。

(Since the comments on the other answer are too constrained) (由于对其他答案的评论过于局限)

First you define a new type for componentType , like this: 首先,为componentType定义一个新类型,如下所示:

typedef char *stockItem_componentType; // Naming subject to conventions

Now in your structure, you use this type instead of simple char* . 现在在您的结构中,您将使用此类型而不是简单的char* This is optional, but very much recommended. 这是可选的,但是非常推荐。 Like this: 像这样:

typedef struct stockItem {
    stockItem_componentType componentType;
    char *stockCode;
    int numOfItems;
    int price;
} stockItem;

And finally, your function prototype is: 最后,您的函数原型是:

struct inventory* searchForItem(stockItem_componentType code);

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

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