gpt4 book ai didi

c - 在C中迭代二维数组

转载 作者:行者123 更新时间:2023-11-30 17:47:42 25 4
gpt4 key购买 nike

我有一个包含字符串值的二维数组。我在迭代时使用枚举来跟踪数组的第一个索引。我试图找到给定字符串匹配的枚举(数组的第一个维度)。现在,我迭代数组并检查值的方式似乎并不是 100% 有效,因为它会返回错误的枚举。有谁知道我做错了什么,或者知道有更好的方法来根据第二个匹配的字符串获取第一个数组的索引吗?

注意:我使用的是 Arduino,并且使用 String 对象而不是 char*。

    enum conditionType {
CLEAR = 0,
OVERCAST,
CLOUDY,
RAIN,
THUNDERSTORM,
SNOW
};

int conditionsIndex[6] = {
CLEAR, OVERCAST, CLOUDY, RAIN, THUNDERSTORM, SNOW};

const char *conditions[][20] = {
// CLEAR
{
"Clear" }
,
// OVERCAST
{
"Partly Cloudy" }
,
// CLOUDY
{
"Shallow Fog",
"Partial Fog",
"Mostly Cloudy",
"Fog","Overcast",
"Scattered Clouds" }
,
// RAIN
{
"Drizzle",
"Rain",
"Hail",
"Mist",
"Freezing Drizzle",
"Patches of Fog",
"Rain Mist",
"Rain Showers",
"Unknown Precipitation",
"Unknown",
"Low Drifting Widespread Dust",

"Low Drifting Sand" }
,
// THUNDERSTORM
{
"Thunderstorm",
"Thunderstorms and Rain",
"Thunderstorms and Snow",
"Thunderstorms and Ice Pellets",
"Thunderstorms with Hail",
"Thunderstorms with Small Hail",
"Blowing Widespread Dust",
"Blowing Sand",
"Small Hail",
"Squalls",
"Funnel Cloud" }
,
// SNOW
{
"Volcanic Ash",
"Widespread Dust",
"Sand",
"Haze",
"Spray",
"Dust Whirls",
"Sandstorm",
"Freezing Rain",
"Freezing Fog",
"Blowing Snow",
"Snow Showers",
"Snow Blowing Snow Mist",
"Ice Pellet Showers",
"Hail Showers",
"Small Hail Showers",
"Snow",
"Snow Grains",
"Low Drifting Snow",
"Ice Crystals",
"Ice Pellets" }
};




int currentCondition;
for ( int i = 0; i < ( sizeof(conditionsIndex) / sizeof(int) ); i++ ) {
int idx = conditionsIndex[i];
for (int j = 0; j < ( sizeof(conditions[idx]) / sizeof(String) ); j++ ) {
if ( forecast.equals(conditions[idx][j]) ) {
currentCondition = idx;
}
}
}

最佳答案

首先,条件是一个 6 x 20 的字符串指针矩阵。有些行(例如 cloudy)仅分配了一个指针(共 20 个)。因此循环需要测试 null ptr 并转到下一行。

不会编写您的代码,但在伪代码中它应该类似于:

 memfill(conditions, 0, 6*20*sizeof(char *));
for (i = 0 to 5)

for (j = 0 to 20)

if (conditions[i][j] == NULL) {break;}

print("%s/n", conditions[i][j]);
// test/compare strings, i is the enum value if a match
// return i;

end for j

end for i

关于c - 在C中迭代二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18840283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com