Pages: [1]   Go Down
Author Topic: Storing strings of various lengths - am I doin' it right? (pointers)  (Read 318 times)
0 Members and 1 Guest are viewing this topic.
Birmingham, UK
Offline Offline
Newbie
*
Karma: 1
Posts: 48
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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:
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:
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
Logged

Valencia, Spain
Offline Offline
Faraday Member
**
Karma: 142
Posts: 5282
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

The last one...
Logged

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

Birmingham, UK
Offline Offline
Newbie
*
Karma: 1
Posts: 48
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Cool, thanks! smiley
Logged

Germany
Offline Offline
Faraday Member
**
Karma: 56
Posts: 2973
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
Code:
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:
Serial.prinln(allMyPhrases[myPhraseOffsets[i]]);

Real RAM saving goes with PROGMEM, though.
Logged

Pages: [1]   Go Up
Jump to: