Question

I am an Arduino noob attempting to select a random name from this array:

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"};

But I receive this error, and I am not sure about different data types and how to approach fixing this array:

error: initializer-string for array of chars is too long

Is there something basic that I am missing?

Was it helpful?

Solution

It is exactly what it is informing: your character strings are way too long to fit in your char array, so your compiler is telling you that it will not proceed any further.

You can make it work by enhancing the size of your arrays like this:

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

The 30 here is just to represent your biggest char string; it needs to have the size of your largest predefined char string + 1 (so that the null terminating character \0 can be added). For example, if your biggest string were "apple", your array would need to be of, at least, length 6.

You can iterate through these strings by doing this, for example:

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");
}

OTHER TIPS

That [3] means each string is limited to a maximum of 3 characters. And since one has to be the null terminator, it really means two. Your strings are a lot longer than that. Choose a number that's big enough to accommodate all of them.

ETA: @JLF: are you my long lost brother? :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top