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.
For the code:
char sweat[] ="Sweater";
warenkorb = new WareImKorb(new Textil (205366,4.2,sweat,40),2,warenkorb);
sweat[0] = '\0';
now if i instead make it:
char* sweat ="Sweater";
the program runs fine till i try sweat[0] = ‘\0’;
It simply crahes then.
However this works:
char cc[] =”Sweater”;
char* sweat = cc;
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.
Here
sweatpoints to a CONSTANT data. “Sweater” is const literal data, residing somewhere in read-only memory, andsweatpoints to this data as such. It doesn’t make a copy of it. So when you dosweat[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 writeconstin your declaration, asconst char* sweater = "Sweater". See the warning here : http://www.ideone.com/P47vvBut 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!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:
Output:
Means, both printfs print the same address!
See yourself here : http://www.ideone.com/VcyM6