You need to enable JavaScript to run this app. C语言遍历结构体数组时指针加结构体大小却偏移3个索引问题求助
优惠活动
大模型
产品
解决方案
定价
更多

C语言遍历结构体数组时指针加结构体大小却偏移3个索引问题求助

问题根因

核心是C语言指针运算的单位规则:指针做加减运算时,偏移量的单位是指针指向类型的大小,不是字节。
你使用的locationpointer是int*类型,指向int数据,你的环境下sizeof(int) = 4,所以locationpointer += 1等价于地址实际偏移4字节,不是1字节。

你需要偏移8字节(也就是sizeof(struct square)的大小)才能到下一个结构体的location成员,按指针运算规则,只需要加8 / sizeof(int) = 2即可。你写的sizeof(struct square)/3刚好因为整数除法取整得到2,属于误打误撞的可运行写法,不是正确逻辑。

你观察到的「加sizeof(struct square)每次偏移3个元素」的现象:

sizeof(struct square)是8,int*加8等价于地址偏移 8 * 4 = 32 字节,每个结构体大小为8字节,32字节对应跳过4个结构体,相当于从当前元素直接跳到了后面第4个元素,中间正好跳过3个元素,和你观察到的现象完全吻合。

修复方案

方案1:直接修正偏移逻辑(最小改动)

把locationfinder中的偏移行改成以下任意一种:

// 写法1:按int指针单位计算偏移
locationpointer += sizeof(struct square) / sizeof(int);

// 写法2:先转char*按字节偏移,逻辑更直观,兼容性更好
locationpointer = (int*)((char*)locationpointer + sizeof(struct square));

方案2:改用结构体指针遍历(推荐,可读性更高)

直接修改locationfinder的参数类型为结构体指针,完全避免指针单位混淆的问题:

  1. 先修改函数声明:
char * locationfinder(struct square * sqptr, int reference);
  1. 调用时传入结构体首地址,替换原来的&table.array[0][0].location:
char * editor = locationfinder(&table.array[0][0], move);
  1. 重写locationfinder的遍历逻辑:
char * locationfinder(struct square * sqptr, int reference)
{
    int runtime = height*width;
    for(int i = 0; i < runtime; i++)
    {
        if(sqptr->location == reference)
        {
            return &sqptr->input;
        }
        sqptr += 1; // 自动偏移一个struct square的大小,无需手动计算偏移
    }
    // 原错误处理逻辑
    char m = 'm';
    return &m;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 12:54:10