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

C++通过首元素指针与元素大小访问结构体数组指定元素的数值问题

问题本质

你遇到的是C/C++指针算术的默认单位问题:

  • 代码中sensorData[0].valueToDisplay是int*类型,C/C++中对T类型的指针做p + n操作时,默认偏移量是n * sizeof(T)字节,也就是你直接对int*加数值,每加1会往后跳4字节(32位int场景下),而不是1字节。
  • 你原本的逻辑是要按字节偏移计算目标地址,所以直接用int*做加法会导致实际偏移量被放大了sizeof(int)倍,除了索引0(偏移为0)之外,其他索引的地址全部偏移错误,访问到了非法内存。

修复方案

只需要在做地址计算前,先把指针强制转换为char*类型即可:char*的大小是1字节,对char*做加法的偏移单位就是1字节,完全匹配你按结构体大小算字节偏移的逻辑。
修改问题行代码为:

elementToDisplay = (char*)sensorData[0].valueToDisplay + (sensorData[0].arrayElementSize * thermistorIndex);

修改后运行输出为:

10, 10
10, 20

完全符合预期。

完整修改后代码

#include <iostream>
using namespace std;

struct thermistors_t{
  int itemIDNo;
  int  valueToDisplay;
  int noOfSamples;};

thermistors_t thermistors[]{
    {1, 10, 100},
    {2, 20, 200},
    {3, 30, 300}};

struct sensorData_t{
  int itemIDNo;
  int *valueToDisplay;
  int arrayElementSize;};
  
const sensorData_t sensorData[]{
    {1, &thermistors[0].valueToDisplay, sizeof(thermistors_t)}};


void display_value(int thermistorIndex){
  void *elementToDisplay;
  int *intToDisplay;

  // 仅修改这一行,先转char*再做字节偏移计算
  elementToDisplay = (char*)sensorData[0].valueToDisplay + (sensorData[0].arrayElementSize * thermistorIndex);
  intToDisplay = (int*)elementToDisplay;
  cout << *sensorData[0].valueToDisplay << ", ";
  cout << *intToDisplay << '\n';
}


int main() 
{
  display_value(0);
  display_value(1);
  return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 20:36:04