Allocating strings to RAM?



  • Avatar
    Trevor O'Grady

    #define MAX_STRINGS 12

    #define MAX_STRING_SIZE   10

    char PrefsUser[MAX_STRINGS][MAX_STRING_SIZE + 1] = {"100", "30", "4", "2", "Blue", "Green", "Red", "White", "Blue", "Red", "1", "~"};


    From your example I'm not sure if you need the strings or the pointers to the strings to be variable (i.e. in RAM). A higher level view of what you are trying to achieve would be useful in order to best advise. Maybe supply more code (even if it does not work/compile) along the lines of what you want to do.

    Regards, Trevor

    Comment actions Permalink
  • Avatar
    Michael Jones

    Thanks, Trevor.


    Paul Curtis of Rowley already responded to my request. If I may, I'll quote his suggestion, as I've been using his tip with great success:


    Paul Curtis, Dec 31 11:02 am (GMT):

    In C, quoted string literals may be placed in RAM or in read-only memory by the compiler. The above is allowed because originally K&R C did not have a "const" keyword and C89 and C99 feature backward compatibility.

    How would I do this?

    char Prefs0[25] = "100";
    char Prefs1[25] = "30";
    char Prefs2[25] = "4";

    This allows 25 characters per preference setting and initializes the preference.

    Now, you need:

    char *PrefsUser[] = { Prefs0, Prefs1, Prefs2...

    Note that the array in PrefsLimits will be stored in RAM (as it is not const). This is hard for some people to grasp, and I've seen it time and again. As such, to reduce RAM usage, you might want:

    const char * const PrefsLimits[] = ...


    char * const PrefsUser[] = ...

    Comment actions Permalink
  • Avatar
    Trevor O'Grady

    Yes, Paul's suggestion is very similar to mine. How exactly I'd do this depends on how you are going to use the arrays.




    Comment actions Permalink

Please sign in to leave a comment.