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" .

Parents
  • 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"
    

Reply
  • 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"
    

Children