c++ - 字符字符串数组的初始化程序中的问题

标签 c++ c arrays arduino

我是一个 Arduino 菜鸟,试图从此数组中选择一个随机名称:

char ns[ ][3] = {"Carlos Alberto Castronovo","Tom Erbaugh","Caterina De Giacco","Di Puglia Pugliese Filomena","Manishwar Dhillon","Mel Richards","Connie Hvidtfeldt","Amy Namehere","Tim Beck","Sanil Sethi","Christophe Lavault","Steven Grimes","Jessica Serra","Mariateresa Petrucci","Patricia Anderson","Felma Roberto Cinco","Mai Ahmed","Tobe Levy","Indah Suspriati Wibawa","Dain Turgeon Orbe","Li Wang","Ed Clark","Elodie da Silva","Jason Garcia","Allan Litswa","Pietro Zubani","Cyril Jeanpierre","Kate Denali Princess","Maria Pilar Gl","Jefferson Ricarte","Adam Reed","László Lipták","Thalia Dbl","Maria Jose Calle Salas","William Alexander","Nicole Richardson","Andrea Hescher","Ismail Sholeh","Simone Spacci","Jason Jankow"};

但是我收到此错误,并且我不确定不同的数据类型以及如何修复此数组:

错误:字符数组的初始化字符串太长

我缺少一些基本的东西吗?

最佳答案

这正是它所传达的信息:您的字符串太长,无法放入 char 数组中,因此编译器告诉您它将不再继续进行。

您可以通过增加数组的大小来使其工作,如下所示:

char ns[ ][30] = //... ;

这里的30只是代表你最大的字符串;它需要具有最大预定义字符串的大小 + 1 ( so that the null terminating character \0 can be added )。例如,如果最大的字符串是 "apple",则数组的长度至少需要为 6

您可以通过执行以下操作来迭代这些字符串,例如:

int array_items = sizeof(ns) / sizeof(*ns); // this will gives you the amount of items stored in your array
int i;
int j;
for (i = 0; i < array_items; ++i) {
   size_t strSize = strlen(ns[i]); // strSize now contains, if ns[i] contained the example of apple, 5
    for (j = 0; j < strSize; ++j) {
        printf("%c", ns[i][j]);
    }
  printf("\n");
}

关于c++ - 字符字符串数组的初始化程序中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23281584/

相关文章:

c++ - 如何准确理解函数递归?

c++ - 为什么应该使用命令行参数?

c++ - 如何知道字符串中的单词是否有数字?

c - 对于数组,为什么会出现 a[5] == 5[a] 的情况?

css - 使用 CSS 表 (GTK+3) 更改 GtkToggleToolButton 的文本颜色

java - 发送对同一类中另一个方法的引用的建议

ruby-on-rails - 如何允许数组具有强参数

c++ - 凹面 GL_POLYGON 不着色?

c++ - ALLEGRO 中 al_draw_line() 失败

php - PHPs IteratorAggregate 中 getIterator 返回的数组不可遍历