waldol1
waldol1

Reputation: 1881

Making an array of char[] in C

I am working with a wifi microcontroller that needs to serve up a large (20kb) static html page. Because individual buffers on the microcontroller only hold 1.4kb, it is necessary to break up the html into chunks and send the pieces one at a time.

What I have right now is about 100 string assignemnts that look like this:

char HTML_ID_96[] = "\
<p><a href=\"#t\">Return to top</a></p>\
<a id=\"id9\"/>\
<span class=\"s\">Firmware Version/Information</span>\
<span class=\"c i\" id=\"id9-h\" onclick=\"h(\'id9\');\">hide</span>&nbsp;\
<span class=\'c\' id=\"id9-s\" onclick=\"s(\'id9\');\">show</span>\
<table class=\"t i\" id=\"id9-table\"><tbody>\
";

I would like a way to impose an iterable sequence on all of the strings by sticking them in an array, but I am not sure how to package them.

I have tried:

char** all = [HTML_ID_1, ..., HTML_ID_99];
char* all[] = [HTML_ID_1, ..., HTML_ID_99];
char all[][] = [HTML_ID_1, ..., HTML_ID_99];

But none of them compile. Any references to how C handles arrays is a bonus.

Extension:

char const* HTML_ID_100 = "\
</form>\
</body>\
</html>\
";

char const* all[] = {HTML_ID_100};

Is not compiling. I'm using gcc 3.4.4. Two errors are reported: "initializer element is not constant" and "(near initialization for 'all[0]')". Both occurring on the last line shown.

Upvotes: 1

Views: 168

Answers (3)

Michael Burr
Michael Burr

Reputation: 340178

An array of pointers to string:

char* all[] = {HTML_ID_1, ..., HTML_ID_99};

Note that you may want to terminate the array with a NULL pointer depending on how you're going to iterate over the array:

char* all[] = {HTML_ID_1, ..., HTML_ID_99,NULL};

Also, if the strings aren't going to be modified, you can save some data space by declaring them as simple pointers to the literal strings instead of arrays of char that are initialized by the literal:

char const* HTML_ID_96 = "\
<p><a href=\"#t\">Return to top</a></p>\
<a id=\"id9\"/>\
<span class=\"s\">Firmware Version/Information</span>\
<span class=\"c i\" id=\"id9-h\" onclick=\"h(\'id9\');\">hide</span>&nbsp;\
<span class=\'c\' id=\"id9-s\" onclick=\"s(\'id9\');\">show</span>\
<table class=\"t i\" id=\"id9-table\"><tbody>\
";

Upvotes: 4

stevenstevensteven
stevenstevensteven

Reputation: 330

You're on the right track but you need to use curly braces for a static array declaration. This should work:

char* all[] = {HTML_ID_1, ..., HTML_ID_99};

An example

I would think about what you are doing and if there is a better way to do it though. E.g. if it is a micro, can you make a large array in program memory (i.e the NVRAM) and read from it serially?

Upvotes: 2

Andy Thomas
Andy Thomas

Reputation: 86381

Use braces for array initialization.

char* all[] = { HTML_ID_1, ..., HTML_ID_99 };

Upvotes: 8

Related Questions