传递结构项作为参数

时间:2016-03-29 17:01:36

标签: c

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

但是是否可以预设参数,因此只能传递特定的结构项:

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

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

编辑:

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

2 个答案:

答案 0 :(得分:2)

该组件的类型为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后面的指针,不建议这样做。然后,阅读你的代码(包括你自己)的人不会仅仅通过查看它就知道它是一个指针,这会导致混乱。

答案 1 :(得分:2)

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

首先为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);
相关问题