【问题标题】:Assign member values of struct from pointer从指针分配结构的成员值
【发布时间】:2012-10-23 01:24:39
【问题描述】:

我有一个结构和一个函数,它返回一个指向它读取的结构的指针:

typedef struct cal_t {
    float xm; 
    float ym; 
    float xn; 
    float yn; 
} cal_t;


struct cal_t *lld_tpReadCalibration(void);

在其他地方,我确实有该结构的一个实例:

struct cal_t cal;

现在我需要将该结构实例的值分配给我得到返回指针的结构的值。所以我想要的是 cal.xm 与 lld_tpReadCalibration() 中的 cal->xm 的值相同。象征性地:

struct cal_t cal;

cal = lld_tpReadCalibration();

但这当然行不通:

error: incompatible types when assigning to type 'volatile struct cal_t' from type 'struct cal_t *'

我怎样才能按照我想要的方式进行这项工作?

感谢您的帮助。

【问题讨论】:

    标签: c pointers struct assign


    【解决方案1】:

    您需要以某种方式取消对指针的引用。您正在从函数中取回一个指针,因此您正在寻找* 运算符或->,这当然是* 的同义词。

    您将cal 定义为struct cal_t,该函数返回一个指向cal_t 的指针。所以你需要取消引用指针。

    cal = *lld_tpReadCalibration();
    

    【讨论】:

      【解决方案2】:

      函数返回值为struct cal_t *,为指针类型。

      因此,您应该将返回值分配给类型为 struct cal_t * 的变量。

      例如,

      struct cal_t *cal_ptr;
      
      cal_ptr = lld_tpReadCalibration();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-02
        • 1970-01-01
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        相关资源
        最近更新 更多