尝试设置字符数组的字符时程序崩溃 [英] Program crashes when trying to set a character of a char array
问题描述
我有这个我的程序的奇怪的行为,我不能弄清楚。我的教授给我一个在我的程序中的缺陷,我只是复制一个字符指针,当我构造一个对象,而不是一个新的副本的整个数组,所以你可以愚弄它。他用类似的代码演示了这个。
I got this weird behavior of my programm, that i cant figure out. My professor showed me a flaw in my programm, where i just copy a char pointer when i construct an object instead of making a new copy of the whole array, so you can fool around with it. He demonstrated this with similar code like this.
对于代码:
char sweat[] ="Sweater";
warenkorb = new WareImKorb(new Textil (205366,4.2,sweat,40),2,warenkorb);
sweat[0] = '\0';
现在如果我改为:
char* sweat ="Sweater";
程序运行正常,直到我试试sweat [0] ='\0';
the program runs fine till i try sweat[0] = '\0'; It simply crahes then.
但是,这是有效的:
char cc [] =Sweater;
char * sweat = cc;
However this works: char cc[] ="Sweater"; char* sweat = cc;
这真的让我很烦,我不明白,为什么版本1不工作。
It is really bugging me, that i dont understand, why version 1 does not work. Hope you guys can help me out, or else i will go crazy wondering about this.
推荐答案
char* sweat ="Sweater";
sweat[0] = '\0'
汗水指向一个CONSTANT数据。 Sweater是const文本数据,驻留在只读存储器中的某处,并且 sweat
指向此数据。 它不会复制它。因此,当你做 sweat [0] ='\0'
,它试图改变CONSTANT数据的字符。因此错误。顺便说一句,一个好的编译器应该给出警告,如果你不写 const
在你的声明,如 const char * sweater =Sweater
。请参阅此处的警告: http://www.ideone.com/P47vv
Here sweat
points to a CONSTANT data. "Sweater" is const literal data, residing somewhere in read-only memory, and sweat
points to this data as such. It doesn't make a copy of it. So when you do sweat[0]='\0'
, it tries to change first character of the CONSTANT data. Hence the error. By the way, a good compiler should give warning if you don't write const
in your declaration, as const char* sweater = "Sweater"
. See the warning here : http://www.ideone.com/P47vv
但是当你写 char sweat [] =Sweater
时,会创建一个char数组,从CONSTANT数据复制数据毛衣
;该数组的元素本身是可修改的!
But when you write char sweat[] = "Sweater"
, an array of char is created, copying the data from the CONSTANT data which is "Sweater"
; that array's element itself is modifiable!
让我们看一个有趣的事情:因为在第一种情况下,它不会复制const数据,所以无论你声明多少个变量(都指向同一个数据),所有变量的地址都是相同的。请参阅:
Lets see an interesting thing: since in the first case, it doesn't make a copy of the const data, so no matter how many variables you declare (all pointing to the same data), the address would be same for all variables. See this:
#include<cstdio>
int main() {
char* sweat ="Sweater"; //notice the warning
const char* another ="Sweater"; //no warning!
std::printf("%p\n", sweat); //print the address
std::printf("%p\n", another); //print the address
return 0;
}
输出:
0x8048610
0x8048610
相同的地址!
在这里查看自己: http:// www.ideone.com/VcyM6
这篇关于尝试设置字符数组的字符时程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!