为什么可以';我是否使用函数计算的int作为索引来访问此数组中的值? 编辑:我错误地假设我应该把这个问题作为一个通用的C++问题来解决,后来才意识到这个问题来自我在ARDUNO环境中使用C++。在我的示例中,我没有在阵列上使用Arduino ModifierPROGMEM,该阵列将其存储从RAM移动到闪存,这最终导致了计算问题。访问PROGMEM数组需要我使用存取器方法pgm\u read\u byte而不是索引
我有一个数组:为什么可以';我是否使用函数计算的int作为索引来访问此数组中的值? 编辑:我错误地假设我应该把这个问题作为一个通用的C++问题来解决,后来才意识到这个问题来自我在ARDUNO环境中使用C++。在我的示例中,我没有在阵列上使用Arduino ModifierPROGMEM,该阵列将其存储从RAM移动到闪存,这最终导致了计算问题。访问PROGMEM数组需要我使用存取器方法pgm\u read\u byte而不是索引,c++,arduino,adafruit,C++,Arduino,Adafruit,我有一个数组: const PROGMEM uint8_t daysInMonth[12]={31,28,31,30,31,31,31,30,31}; 我有一个从时间库计算的功能uint8: uint8_t month=tm.month() 我有一个尺码: size\u t monthIndex=(size\u t)月 我尝试使用month或monthIndex访问此数组中的值,但结果相同: # For size_t monthIndex = 1 or uint8 month = 1; ...
const PROGMEM uint8_t daysInMonth[12]={31,28,31,30,31,31,31,30,31};
我有一个从时间库计算的功能uint8:
uint8_t month=tm.month()代码>
我有一个尺码:
size\u t monthIndex=(size\u t)月代码>
我尝试使用month
或monthIndex
访问此数组中的值,但结果相同:
# For size_t monthIndex = 1 or uint8 month = 1; ...
uint8_t currentDaysInMonth = daysInMonth[monthIndex];
# >> Expected = 28;
# >> What I actually get = 61;
如何获得预期的数组值
61来自哪里
编辑
这是tm
DateTime类的相关部分
class DateTime {
public:
DateTime (uint16_t year, uint8_t month, uint8_t day,
uint8_t hour = 0, uint8_t min = 0, uint8_t sec = 0);
uint8_t month() const { return m; }
}
日期时间构造函数
DateTime::DateTime (uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t min, uint8_t sec) {
if (year >= 2000)
year -= 2000;
yOff = year;
m = month;
d = day;
hh = hour;
mm = min;
ss = sec;
}
最简单的例子:
DateTime tm = DateTime(2020, 2, 1, 0, 0, 0);
const PROGMEM uint8_t daysInMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
uint8_t month = tm.month();
uint8_t currentDaysInMonth = daysInMonth[month];
>> currentDaysInMonth Returns 61
>> expect 31 from this example, though would offset index - 1 once I figure out what the issue is.
打印日志:
std::cout << month << std::endl;
std::cout << tm.month() << std::endl;
std::cout << currentDaysInMonth << std::endl;
# >> 2
# >> 2
# >> 219 -- sometimes its 61, 45, 219, not sure the rhyme or reason to this value
std::cout 219——有时是61、45、219,不确定该值的押韵或原因
> p>我错误地假设我应该把这个问题作为一个通用的C++问题,后来才意识到这个问题来自于我在ARDUNO环境中使用C++。在我的示例中,我没有在阵列上使用Arduino Modifier PROGMEM,它将存储从RAM移动到闪存,这最终导致了计算问题。访问PROGMEM数组需要我使用存取器方法pgm_read_byte而不是索引
解决方案:
DateTime tm = DateTime(2020, 2, 1, 0, 0, 0);
const PROGMEM uint8_t daysInMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
uint8_t month = tm.month();
# use the pgm_read_byte accessor
uint8_t currentDaysInMonth = pgm_read_byte(&daysInMonth[month - 1]);
谢谢大家的帮助!很抱歉,最初缺少信息
一些资源:
请在您的问题中添加一个变量,否则您也不需要使用monthIndex
临时变量(从我所能看到的有限信息来看)。您可以直接使用month
作为索引。也可以显示DateTime
构造函数的定义。您只显示了声明。DateTime
根据您的代码没有成员。听着,我们想帮助你,但是如果我们不能编译你给我们的代码(因为它缺少关键方面),那么就几乎不可能知道真正的问题是什么。另一方面,如果你能给我们提供我们可以复制粘贴到的代码,例如,godbolt.org
,并且它再现了这个问题,那么你几乎肯定会得到一个答案:从与你的代码混合的库中很难找到这些代码片段中的错误。您应该制作一个小的、完整的示例,任何拥有Arduino环境的人都可以按原样编译。您不需要包含库代码,只需提到DateTime
来自adafruit RTCLib。另外,在你的问题中添加适当的标签,以吸引可能具备所需知识的人。我在你的问题上加了两个标签。我本来也会添加RTCLib
,但找不到该标记。