更改静态数组
我在文件中声明了一个静态变量:
static char *msgToUser[] = {
"MSG1 ",
"MSG2 ",
};
在一个类的方法之一中,我正在执行以下操作:
void InfoUser::ModifyMsg( BYTE msgIdx, char *msgString ){
strncpy( msgToUser[ idx ], msgString, DISPLAY_SIZE );
}
当我执行 strncopy 时,程序崩溃。我不确定我做错了什么
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您已将 msgToUser 定义为字符指针向量。这些字符指针指向存储在已标记为只读的内存中的字符串(字符数组)(在 Microsoft 的 Visual Studio 中,您可以通过编译器选项更改此设置)。
因此,如果您更改此内存,处理器将引发异常(您正尝试在只读内存中写入),并且您的应用程序将崩溃。
You have defined msgToUser as a vector of char-pointers. These char-pointers point to strings (character arrays) that are stored in memory that has been marked as read-only (In Microsoft's Visual Studio you can change this via a compiler option).
Therefore, if you change this memory, the processor will raise an exception (you are trying to write in read-only memory) and your application will crash.
不要将数组保留为指针数组,而是将其设为二维字符数组,这将使其分配空间。
现在,由于它是一个 char * 数组,并且使用字符串文字进行初始化,因此当您尝试覆盖字符串文字的只读内存时,它会崩溃。
Instead of keeping your array as an array of pointers, make it a two dimensional array of characters which will make it allocate space.
Now, since it is an array of char * and initialization is happening using string literals, when you try to overwrite read only memory of string literals, it crashes.
请参阅 C-常见问题解答。 问题 1.32
See C-FAQ. Question 1.32
您定义的数组是一个指向字符串的指针数组;每个字符串都是一个文字(即,解释为指针的带引号的字符串) - 这意味着它是一个常量,即使您没有这样声明它。您无法修改字符串文字。
如果您希望能够修改它们,可以使用显式数组分配:
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: