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 :idea:
Printable View
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 :idea:
try making it:
You'll have to include string.hCode:strcpy(s, "change");
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]
True. I would have just passed the function a pointer anyway.
And (seeing as how you're using C++) you can do this with a reference too!