尝试设置 char 数组的字符时程序崩溃

Program crashes when trying to set a character of a char array(尝试设置 char 数组的字符时程序崩溃)

本文介绍了尝试设置 char 数组的字符时程序崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序出现了这种奇怪的行为,我无法弄清楚.我的教授向我展示了我的程序中的一个缺陷,我只是在构造一个对象时复制一个 char 指针,而不是制作整个数组的新副本,所以你可以玩弄它.他用类似的代码证明了这一点.

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] = '';

现在如果我成功了:

char* sweat ="Sweater";

程序运行良好,直到我尝试汗水[0] = '';然后它就会崩溃.

the program runs fine till i try sweat[0] = ''; It simply crahes then.

但是这有效:char cc[] ="毛衣";char* 汗水 = 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] = ''

这里的sweat 指向一个CONSTANT 数据.毛衣"是常量字面量数据,驻留在只读内存中的某处,而 sweat 就这样指向该数据.它不会复制它.因此,当您执行 sweat[0]='' 时,它会尝试更改 CONSTANT 数据的第一个字符.因此错误.顺便说一句,如果你没有在声明中写 const,一个好的编译器应该会给出警告,例如 const char* shirt = "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]='', 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 shirt[] = "Sweater" 时,会创建一个char 数组,从"Sweater" 的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
", sweat);     //print the address
        std::printf("%p
", another);   //print the address
        return 0;
}

输出:

0x8048610
0x8048610

意味着,两个 printfs 都打印相同的地址!

Means, both printfs print the same address!

在这里看到自己:http://www.ideone.com/VcyM6

这篇关于尝试设置 char 数组的字符时程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:尝试设置 char 数组的字符时程序崩溃

基础教程推荐