Go Down

Topic: Storing strings of various lengths - am I doin' it right? (pointers) (Read 381 times) previous topic - next topic

howiem

Absolute newbie C question. I need to store some static phrases to put on a display, but the lengths of them vary. Which of these options is the best way to store the strings?

Code: [Select]
char myPhrases[][]= {"hello","goodbye","please go away"};

// I think this would allocate 15 characters (ie length of the longest string)
// to every string whether needed or not - is that correct?


Then I tried:

Code: [Select]
char allMyPhrases[] = "hello\0goodbye\0please go away\0";
char* myPhraseOffsets[] = {0,6,14};

// This ought to be as space-efficient as possible, but it's a
// pain to change one of the first phrases as you have to
// re-count all the offsets by eye


But this seems to work, too, and kinda looks more correct as well as being more programmer friendly:

Code: [Select]
char* myPhrases[]={"hello","goodbye","please go away"};

// but I can't tell if it's padding the strings or not.


When I google "storing strings of different lengths" I end up with results that seem overly complicated, linked lists and vectors and stuff. What's the standard C programmer's approach to this?

(I know that as the phrases are static, I ought to put them into the PROGMEM bit of the chip, but that can come later once I've sussed this pointers malarkey)

Thanks, h

fungus

No, I don't answer questions sent in private messages (but I do accept thank-you notes...)


michael_x

Quote

Code: [Select]
char allMyPhrases[] = "hello\0goodbye\0please go away\0";
char* myPhraseOffsets[] = {0,6,14};

// This ought to be as space-efficient as possible, but it's a
// pain to change one of the first phrases as you have to
// re-count all the offsets by eye



If you had byte myPhraseOffsets[] = {0,6,14};
you would have saved 3 bytes, compared to the "Cool" solution with 3 char* to the different strings.
Costs a bit more typing in usage

Code: [Select]
Serial.prinln(allMyPhrases[myPhraseOffsets[i]]);

Real RAM saving goes with PROGMEM, though.

Go Up