繁体   English   中英

传递结构项作为参数

[英]Passing a struct item as the parameter

我知道可以将结构作为参数传递。

但是是否可以预先设置参数,以便只能传递特定的结构项,例如:

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

我得到:错误:预期为';' ,','在令牌之前

编辑:

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

该组件的类型为char * ,因此只需使该参数为类型即可。

struct inventory* searchForItem(char *code){

如果要使类型更严格,请为相关字段创建一个typedef:

typedef char * stockItem_componentType;

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

struct inventory* searchForItem(stockItem_componentType code){

请注意,这会将指针隐藏在typedef后面,这是不推荐的。 这样一来,阅读您的代码(包括您自己)的人们就不会仅仅通过查看它的指针就知道它是一个指针,这可能导致混乱。

(由于对其他答案的评论过于局限)

首先,为componentType定义一个新类型,如下所示:

typedef char *stockItem_componentType; // Naming subject to conventions

现在在您的结构中,您将使用此类型而不是简单的char* 这是可选的,但是非常推荐。 像这样:

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

最后,您的函数原型是:

struct inventory* searchForItem(stockItem_componentType code);

暂无
暂无

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

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