Modify Static Array

I have a static variable declared in a file:

static char *msgToUser[] = {
    "MSG1                ", 
    "MSG2                ",
};

Inside one of the class methods, I do this:

void InfoUser::ModifyMsg( BYTE msgIdx, char *msgString ){
    strncpy( msgToUser[ idx ], msgString, DISPLAY_SIZE );
}

When I do strncopy, the program crashes. I'm not sure what I'm doing wrong.

+3
source share
4 answers

The array you defined is an array of pointers to character strings; each character string is a literal (i.e. a quoted string interpreted as a pointer) - this means that it is a constant, even if you did not declare it as such. You cannot modify string literals.

If you want to change them, you can use the explicit distribution of the array:

// Note: The space padding isn't needed if all you require is that the string
// be able to hold DISPLAY_SIZE characters (incl the null terminator)
static char str_1[DISPLAY_SIZE] = "MSG1                ";
static char str_2[DISPLAY_SIZE] = "MSG1                ";
static char *msgToUser[] = { str_1, str_2 };
+6

. C-FAQ. 1.32

+2

, , , .

, char *, , , .

0

msgToUser char -pointers. char ( ), , ( Microsoft Visual Studio ).

, , ( ), .

0

Source: https://habr.com/ru/post/1762277/


All Articles