G
Gary
Hi all! I've taken some time on learning the difference between
"pointers to const variables" and "const pointer variables". The
question is: in the following code, can we change the contents of the
const pointer (i.e. t)? I got a segmentation fault in the last for
loop.
I wrote the code in c++, but the language is not the point, right?
Thanks in advance!
#include <iostream>
using namespace std;
main ()
{
const char* s; // pointer to const variable
s = "hello";
for (; *s; s++)
// *s = 'a'; WRONG! the string is const, so it cannot be changed
cout << *s << endl;
s = "world"; // OK! reassign s to another string. the pointer is
not const
for (; *s; s++)
cout << *s << endl;
char* const t = "welcome"; // const pointer
int i = 0;
// t = "abcd"; // WRONG! t is read-only
for (; *(t+i); i++)
{
if (*(t+i) == 'o') // ????????? I suspect I can do this, but why
segmentation fault ??????????
*(t+i) = 'a'; // change "welcome" to "welcame"
cout << *(t+i);
}
cout << endl;
}
"pointers to const variables" and "const pointer variables". The
question is: in the following code, can we change the contents of the
const pointer (i.e. t)? I got a segmentation fault in the last for
loop.
I wrote the code in c++, but the language is not the point, right?
Thanks in advance!
#include <iostream>
using namespace std;
main ()
{
const char* s; // pointer to const variable
s = "hello";
for (; *s; s++)
// *s = 'a'; WRONG! the string is const, so it cannot be changed
cout << *s << endl;
s = "world"; // OK! reassign s to another string. the pointer is
not const
for (; *s; s++)
cout << *s << endl;
char* const t = "welcome"; // const pointer
int i = 0;
// t = "abcd"; // WRONG! t is read-only
for (; *(t+i); i++)
{
if (*(t+i) == 'o') // ????????? I suspect I can do this, but why
segmentation fault ??????????
*(t+i) = 'a'; // change "welcome" to "welcame"
cout << *(t+i);
}
cout << endl;
}