Apparently I'm a member of a large club that just doesn't understand C-style pointers correctly. Here's my program:
void changethestring (const char * thestring)
{
thestring = "string two";
}
int _tmain(int argc, _TCHAR* argv[])
{
const char * teststring = "string one";
changethestring(teststring);
printf("The string is: %s.\n", teststring);
return 0;
}
My intent is that changethestring() should cause the pointer to point to "string two". My logic is that I'm giving the function a pointer. The function should be able to change the pointer to point to a different area in memory. And that change should persist outside the function.
Yet that's not what happens. In the printf() statement, the string is still "string one".
Can anyone explain why this is, what's happening under the covers, and how I can write a function changethestring() to change the string to which the pointer points?
thestring
points to the string. You need to change the pointer itself. Pass aconst char **
and change the line to*thestring = "string two"
then call withchangestring(&teststring)
teststring
(having address 0) contains, some memory address, say200
, now you gave that address to some another variablethestring
(having address 4) (here,thestring
got one copy of what is held byteststring
). Now what changed you made at address 4, remained at address 4. Though what you are trying to access inmain
is actually at address 0. I hope it makes some sense.