-
modifying strings
Could any reader kindly (very kindly( tell me why function modifyNm() is not modifying the name from Bob to John. When I get the output for main() it still oututs Bob instead of John. I know we can modify and reinitialize int type arrays by calling a function. Is there something special about strings that I am not aware of - most probably there is. Please help, thanks a million.
void modifyNm(char *name)
{
name = "John";
}
int main()
{
clrscr();
char nm[10]; = "Bob";
modifyNm(nm);
cout << nm;
getch();
return 0;
}
-
It's because you aren't changing the string itself, in the function you are changing the pointer.
So, the whole things works like this:
* nm contains "Bob\0" and has 10 bytes allocated to it.
* You pass the address where nm is located, and this address is stored in the pointer name.
* When you do name = "John", you tell the pointer name to point at the location of "John\0" in memory. This doesn't alter the original string at all, it only changes what you point to.
* When you return, your array is still unchanged.
To fix this, you want to modify the string that the pointer points to, you DON'T want to change the value of the pointer itself. Do this:
strcpy(name,"John");
instead of
name = "John";
The first one copies the literal string "John" into the memory that name points to (which changes nm because this is nm's allocated memory), the second one merely makes name point somewhere else, which won't change nm at all.
-
Here, this image I tossed together might explain it better.
The top shows you how the strings are in memory in your current system. This shows the memory contents of two locations -- your allocated space, nm, plus the (automatically) allocated literal string "John/0" -- all string literals will be put in your program's data section and loaded when your program begins.
The bottom shows how the code I suggested works.
I hope this is clear.