Results 1 to 5 of 5
Code:
void change(char *s)
{
s="change";
}
int main()
{
char *p="abc";
change(p);
cout<<p;
return 0;
}
according 2 me the ouput should be change but the outoput is abc
...
Enjoy an ad free experience by logging in. Not a member yet? Register.
- 09-15-2005 #1Linux Newbie
- Join Date
- Mar 2005
- Location
- Bangalore, INDIA
- Posts
- 122
pointer magic
according 2 me the ouput should be change but the outoput is abcCode:void change(char *s) { s="change"; } int main() { char *p="abc"; change(p); cout<<p; return 0; }
any reasons why
Portability is for people who cannot programme
- 09-15-2005 #2
try making it:
You'll have to include string.hCode:strcpy(s, "change");
- 09-15-2005 #3Linux User
- Join Date
- Aug 2005
- Location
- Italy
- Posts
- 401
Argument by value
All function arguments are passed by value: the value of the argument is copied.
In the routine change, you don't modify the variable p declared in main, but its copy used as argument in the function chage... To modify variables you should use pointers, but because a" string" is just like a pointer, you must use a double pointer.
A solution can be...
[code]
void change(char **s) /* double pointer! */
{
s="change";
}
int main()
{
char *p="abc";
change(&p); /* we must pass a char** */
cout<<p; /* Now prints "change" */
return 0;
}
[code][/code]When using Windows, have you ever told "Ehi... do your business?"
Linux user #396597 (http://counter.li.org)
- 09-15-2005 #4
True. I would have just passed the function a pointer anyway.
- 09-16-2005 #5
And (seeing as how you're using C++) you can do this with a reference too!
Linux user #126863 - see http://linuxcounter.net/


Reply With Quote
