【问题标题】:Array of string array in CC中的字符串数组数组
【发布时间】:2013-08-16 20:32:03
【问题描述】:

我正在创建一个包含 C 中字符串数组的数组。我有一个名为 conditionType 的枚举,用于通过条件数组的第一个索引进行访问。

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

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

const char *conditions[][count] = {
  // CLEAR
  {
    "Clear"  }
  ,
  // OVERCAST
  {
    "Overcast","Scattered Clouds", "Partly Cloudy"  }
  ,
  // CLOUDY
  { 
    "Shallow Fog","Partial Fog","Mostly Cloudy","Fog","Fog Patches","Smoke"  }
  ,
  // 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"  }
};

我是 C 的新手,我想知道这一行需要多少计数

const char *conditions[][count] 

假设每个子数组的大小不同。

【问题讨论】:

标签: c arrays string


【解决方案1】:

简单的解决方案是让子数组大小相同,用“”或NULL填充。

更好的解决方案是分别声明每个子数组,并使conditions 成为指向字符串指针数组的指针数组。字符串指针的每个子数组都以 NULL 结尾以指示其长度。

#include <stdlib.h>
const char *condCLOUDY[] = { "Shallow Fog", "Partial Fog", "Mostly Cloudy", "Fog",
    "Fog Patches", "Smoke", NULL };
const char *condRAIN[] = { "Drizzle", "Rain", "Hail", "Mist", NULL };
// etc.
const char **conditions[] = { condCLEAR, condOVERCAST, condCLOUDY, condRAIN, 
     condTHUNDERSTORM, condSNOW, NULL };

【讨论】:

  • 一个迂腐的解决方案会使数组constconst char * const condCLOUDY[] = { ...const char * const * const conditions[] = { ....
猜你喜欢
  • 1970-01-01
  • 2011-01-22
  • 2011-08-12
  • 1970-01-01
  • 2020-07-18
  • 1970-01-01
  • 2020-12-02
  • 1970-01-01
相关资源
最近更新 更多