【问题标题】:C : Working with structures and pointers , error : invalid type argument of unary ‘*’C:使用结构和指针,错误:一元“*”的类型参数无效
【发布时间】:2011-12-03 14:38:21
【问题描述】:

我正在开发一个 c 程序,这是我正在使用的结构

struct EngineParts{

    int serial_number;
    unsigned int year_of_manufacture;
    unsigned int quantity;
    char *material;

}*Eparts;

我收到以下错误

`Automobile.c:79:5: error: invalid type argument of unary ‘*’ (have ‘unsigned int’)` 

`Automobile.c:80:5: error: invalid type argument of unary ‘*’ (have ‘int’)` 

`Automobile.c:81:5: error: invalid type argument of unary ‘*’ (have ‘unsigned int’)`

在这三行中

 *new->quantity = quantity;
 *new->serial_number = serial_number;
 *new->year_of_manufacture = year_of_manufacture;

这是完整的实现

void automobile_add_part(const int serial_number,
        const unsigned int year_of_manufacture,
        const unsigned int quantity , 
        const char *material){
    /*
     * Store the address to the latest part
     */
   struct EngineParts *new ;
   new = (Eparts+available_number_of_parts);

    // Copying a String is a little bit complicated
    // First memory is allocated for the string 
    *new->material = (char *)calloc(strlen(material),sizeof(char));
    //Then the string is copied
    strcpy((char *)*new->material,material);    

    *new->quantity = quantity;
    *new->serial_number = serial_number;
    *new->year_of_manufacture = year_of_manufacture;

    available_number_of_parts++;
}

PS: 我检查了以下问题,

error: invalid type argument of ‘unary *’ (have ‘int’)

Invalid type argument of -> C structs

但他们似乎没有帮助我。

关于如何解决问题的任何建议?

【问题讨论】:

    标签: c pointers struct


    【解决方案1】:

    -> 运算符已经为您取消引用指针。

    new->serial_number 等价于(*new).serial_number,两者看起来都是你想要的。

    【讨论】:

      【解决方案2】:

      这样做:

      new->quantity = quantity;
      

      额外的指针取消引用 (*new->quantity) 是一个错误:new->quantityint,不是任何类型的指针,因此编译器会抱怨。

      通过operator-> 已经完成了对new 指针的取消引用(拥有一个这样命名的变量是否合法?)。

      【讨论】:

      • 合法的 C 有一个名为 new 的变量。 new 运算符是 C++ 主义。
      • 因为我使用的是纯 c,所以我认为我可以使用 new 作为变量名。
      【解决方案3】:

      -> 运算符取消引用指针,因此不需要使用额外的*。并导致错误。

      【讨论】:

        【解决方案4】:

        new->quantity 不需要 *

        ->(*new).quantity 的快捷方式

        【讨论】:

          猜你喜欢
          • 2012-03-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-31
          相关资源
          最近更新 更多