【问题标题】:copying pointer to a structure in a structure将指针复制到结构中的结构
【发布时间】:2020-10-15 14:15:04
【问题描述】:

我正在使用运行良好的库 libusb,但现在我正尝试在我自己的结构中使用它的结构。我认为问题只是我复制结构的方式,所以可能不需要了解 libusb 的工作原理。 我的结构包含 libusb 结构:

struct device {
  libusb_device *device_handled;
  libusb_device_handle *handle;
  int port[7];
};
typedef struct device device;

和我的功能:

int myfunction(device *device_element)
{
    libusb_device *tempdevice;
    libusb_device_handle *temphandle;
    device_element = malloc(sizeof(device));

    //my code here where I use tempdevice and temphandle

    (&device_element)->device_handled = tempdevice;
    (&device_element)->handle = temphandle;
}

发出的错误来自最后两行,我不太明白为什么。

‘device_element’ is a pointer; did you mean to use ‘->’?
     (&device_element)->handle = temphandle;
                      ^~
                      ->

【问题讨论】:

    标签: c pointers structure


    【解决方案1】:

    您不需要在device_element 之前添加&,因为malloc 返回一个指向已分配结构的指针。所以只需使用:

    (device_element)->device_handled = tempdevice;  
    (device_element)->handle = temphandle;
    

    【讨论】:

      【解决方案2】:

      那里不需要& 运算符。

      随便用

      device_element->device_handled = tempdevice;
      device_element->handle = temphandle;
      

      【讨论】:

      • 它会导致segfault....内存是为device_element分配的,但是是否需要为设备结构中的libusb_device结构和libusb_device_handle分配内存?
      • @wispy 不,不是真的。如果您还有其他问题,您可能需要发布minimal reproducible example
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多