在C中迭代二维数组

时间:2013-09-17 02:20:16

标签: c string multidimensional-array enums arduino

我有一个包含字符串值的二维数组。我在迭代时使用枚举来跟踪数组的第一个索引。我试图找到给定字符串匹配的枚举(数组的第一个维度)。现在,我正在迭代数组并检查值的方式似乎似乎没有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;
           }
         }
       }

2 个答案:

答案 0 :(得分:0)

首先,条件是指向字符串的6乘20矩阵。某些行(例如多云)仅分配了一个指针(20个中的一个)。所以循环需要测试一个空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

答案 1 :(得分:0)

您的代码的另一个问题是您很可能会用完ram。您可能想查看progmem.

相关问题