【问题标题】:How to get size of String array如何获取字符串数组的大小
【发布时间】:2017-04-01 17:10:47
【问题描述】:

我在“Arduino”中创建了一个字符串数组,如下所示:

String commandList[] = {"dooropen", "doorlock"}; 

在我的代码中,我想知道这个数组的大小,我不想像底部代码那样定义这个数组的大小:

#define commandListArraySize 2

我尝试像这样获取这个变量的大小:

int size = sizeof(commandList);

但是返回的size = 12

【问题讨论】:

  • 不要垃圾标签。 Arduino 不是 C,也不完全是 C++。

标签: arrays string arduino


【解决方案1】:

我喜欢模板数组大小变体,因为它不能与指针类型一起使用:

// Solution proposed by @TylerLewis:
#define ARRAY_SIZE(x) sizeof(x)/sizeof(x[0])

// Template based solution:
template<typename T, size_t N> size_t ArraySize(T(&)[N]){ return N; }

int test(String * ptr);

void setup() {
  String arr[] = {"A", "B", "C"};
  Serial.begin(115200);
  Serial.println(ArraySize(arr));  // prints 3
  Serial.println(ARRAY_SIZE(arr)); // prints 3

  test(arr);
}

void loop() {
}

int test(String * ptr) {
  // Serial.println(ArraySize(ptr));  // compile time error
  Serial.println(ARRAY_SIZE(ptr));    // prints 0 as sizeof pointer is 2 and sizeof String is 6
}

【讨论】:

  • 出色的解决方案,让使用唯一的 C 风格方法更安全。
【解决方案2】:

当你询问字符串数组的长度时,sizeof 方法返回数组中所有字符的长度。所以让我们指望这一点:

String commandList[] = {"dooropen", "doorlock"}; 
int a = 0;
int counter = 0;
while(counter < sizeof(commandList)){
  counter += sizeof(commandList[a]);
  a++;
}
int arrayLength = a;

【讨论】:

    【解决方案3】:

    只要你在创建数组的范围内(你没有将数组传递给函数),你就可以使用这个通用宏:

    #define ARRAY_SIZE(x) sizeof(x)/sizeof(x[0])
    

    并像这样使用它:

    String[] myStrings{"Hello", "World", "These", "Are", "Strings"};
    for (size_t i = 0; i < ARRAY_SIZE(myStrings); i++) {
        Serial.println(myStrings[i]);
    }
    

    【讨论】:

      【解决方案4】:
      String commandList[] = {"dooropen", "doorlock"}; 
      
      int size = commandList.length;
      

      【讨论】:

      • 会很好,但不起作用。给出编译错误:‣ 请求'filelist'中的成员'length',它是非类类型'String [15]'
      猜你喜欢
      • 2013-09-14
      • 1970-01-01
      • 2015-11-27
      • 1970-01-01
      • 2018-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      相关资源
      最近更新 更多