You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言结构体指针赋值报错求助:uint16_t成员赋值失败

C语言结构体指针数组赋值错误:uint16_t成员赋值失败

错误原因

编译报错error: invalid type argument of unary '*' (have 'int')的核心问题在于:

  • ota_list.buf_ptr[ota_list.buf_entry].frameLength是直接访问结构体的uint16_t类型成员,本身就是一个数值变量,而非指针类型,完全不需要用*做解引用操作。
  • 前面的Nsdu是数组,数组名等价于指向首元素的指针,所以用*(Nsdu + n)的方式赋值合法,但frameLength是普通成员,不能套用这种写法。

修正代码

把报错的最后一行代码改成直接赋值即可:

ota_list.buf_ptr[ota_list.buf_entry].frameLength = current_frameLength;

完整修正后的代码片段:

uint16_t current_frameLength =0;
uint16_t plc_tx_count = 0;

typedef struct
{
    uint8_t     Nsdu[R_DEMO_APP_NSDU_BUFFER_SIZE];
    uint16_t    position;
    uint16_t    frameLength;
} ota_buff_t;

typedef struct
{
    ota_buff_t  *buf_ptr; // 指向结构体数组的指针
    uint8_t     buf_entry;
} ota_list_t;

ota_list_t  ota_list;

ota_buff_t *rob_buf = malloc(sizeof(ota_buff_t)*5);
ota_list.buf_ptr = rob_buf; // 将结构体数组地址赋值给指针

*(ota_list.buf_ptr[ota_list.buf_entry].Nsdu ) = 0xD0;
*(ota_list.buf_ptr[ota_list.buf_entry].Nsdu +1) = 0xD0;
*(ota_list.buf_ptr[ota_list.buf_entry].Nsdu +2) = plc_tx_count & 0x00FF;
*(ota_list.buf_ptr[ota_list.buf_entry].Nsdu +3) = plc_tx_count >>8; 
// 修正后的赋值语句
ota_list.buf_ptr[ota_list.buf_entry].frameLength = current_frameLength;

补充说明

  • 访问结构体的数组成员时,数组名可作为指针使用,Nsdu等价于&Nsdu[0],通过*(Nsdu + n)能访问数组第n个元素。
  • 访问结构体的普通数值成员(如uint16_t、uint8_t这类非指针类型)时,直接通过.或->访问后就能赋值,不需要解引用。

内容的提问来源于stack exchange,提问作者Rob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 13:32:12