Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing static array

I have a static variable declared in a file:

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

Inside one of the methods of a class I'm doing this:

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

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

like image 708
Megacan Avatar asked Jun 04 '26 04:06

Megacan


2 Answers

The array you have defined is an array of pointers to character strings; each character string is a literal (ie, a quoted string interpreted as a pointer) - this means it's a constant, even if you didn't declare it as such. You cannot modify string literals.

If you want to be able to modify them, you can use an explicit array allocation:

// 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 };
like image 170
bdonlan Avatar answered Jun 05 '26 17:06

bdonlan


See C-FAQ. Question 1.32

like image 43
matli Avatar answered Jun 05 '26 17:06

matli