short, simple and frustrating
hey! i'm trying to make something simple in visual c++ and i know someone will be able to answer this one quickly. Heres my program. Why does it generate an illegal operation when the program runs? If i change the declaration from char *temp5 to char temp5[] it works, but isn't an array just a pointer to the beginning anyways? shouldn't they be the same? i guess not but i'm just wondering why...
#include <iostream>
using namespace std;
void main()
{
char *temp5 = "abc";
temp5[2] = 'd';
cout<<temp5[2];
}
[600 byte] By [
prosh0t] at [2007-11-18 21:42:09]

# 1 Re: short, simple and frustrating
in this case, the literal "abc" ist const. It lives somewhere in the data segment of your app.
if you use temp[], you allocate memory on the stack and that can be changed.
HTH
Richard
# 2 Re: short, simple and frustrating
Originally posted by prosh0t
Why does it generate an illegal operation when the program runs? If i change the declaration from char *temp5 to char temp5[] it works, but isn't an array just a pointer to the beginning anyways? shouldn't they be the same? i guess not but i'm just wondering why...Because when you declare char *temp5 = "abc", you don't declare an array but a pointer to static, initialized data. That data (your string literal) lies in a data segment which is write protected - that's why you get the access violation.
# 3 Re: short, simple and frustrating
wow you guys are good, thanks
# 4 Re: short, simple and frustrating
As gstercken noted, the data resides in protected memory. You
can only read it.
In order to make a change, you need to allocate memory, copy
the data to the memory, and then make the change.
This will work for you:
void main()
{
char temp5[5] = "abc"; // allocate and copy in one statement
temp5[2] = 'd';
cout<<temp5[2];
}