This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

How to make a pointer point to a constant string in RAM

I'm using Keil3 for arm.
1\I wanna change the string's content,eg from "2007" to "2008"
2\I wanna a pointer ,not a array,to point to the string.
But when I do as follows:
char *ptr = "2007";
ptr is in the flash area,so I cann't change the content of the string "2007" .

  • Your issue is not specific to Keil3 but a basic C issue. Please refer to any book on the C language (and the standard library) or check the Keil User Guide for function strncpy().
    You cannot change a string by a simple assignment but you have to use function strncpy(), e.g.:

    #include <string.h>
    #define STRLEN 4
    
    const char *s1 = "2007"; // goes to flash / ROM
    char s2[STRLEN+1]; // includes terminating '\0'
    char *s3 = s2;
    
    strncpy(s2, s1, STRLEN);
    // s2 and s3 now "2007"
    
    strncpy(s2, "2008", STRLEN);
    // s2 and s3 now "2008"
    

  • if I do like this:

    char array[]="2007";//global variable
    char *ptr=array;

    Is there any problem without the "strncpy()"function?

  • char array[]="2007";//global variable
    char *ptr=array;
    

    But ptr is superfluous, isn't it?

    In what situation would you need 'ptr' that you couldn't use 'array' directly?

    Sounds like you need to review the very close similarities between array names & pointers in 'C'...

  • I define a struct for the button in LCD display:

    typedef struct key
    {
        uint16     x;         //x position in LCD
        uint16     y;         //y position in LCD
         uint8     *text;     //button name
          void    (*onOK)(); //press down responsefunction
    struct key     *next;
    }KEY;
    
    
    and then put all the buttons in a linked-list so that I can change focus among the buttons by ptr->text.
    As the lengths of all the text aren't the same,I need to use pointer to save space instead of array.
    But sometimes I wanna change the content of ptr->text,so in the initialization I cann't do as follows:
    ptr->text = "2007";   //"2007" in flash
    
    I now do like this:
     char array[]="2007"; //"2007" in RAM
     ptr->text = array;   //so is *(ptr->text) in RAM.
    
    All these happen because I didn't know that after the sentence:" ptr->text = "2007";",the string "2007" is in the flash.