void changeStr(char *str)
{
str = "D";
}
void changeStr(char **str)
{
*str = "S";
}
char str[] = "Good";
changeStr(str);
cout<<str<<endl;
char *p = str;
//*p = 'j';
changeStr(&p);
cout<<str<<endl;
I just try to change the value of str[] that array. WITHOUT RETURN!
I think the first changeStr just pass in pointer of str, and change that value, but actually it did not change it.
The second I use pointer of pointer but also cannot work.
Let’s take it step by step.
You are creating an array of characters, 5 characters long with the following content:
{ 'G', 'o', 'o', 'd', '\0' }Here, you are passing that array to a function. Since arrays decay into pointers, this call is perfectly OK.
Now, here comes the first issue. You are probably confusing
"D"and'D'. If you want to change the first character in the array you need to do it the following way:This would work fine. Changing the pointer won’t do anything, because it’s a local variable that holds a pointer to the beginning of the array, not the array itself. If you want to replace the entire content of the array with just
{ 'D', '\0' }, you would need to usestrcpy.Now, let’s check the last part. Here you mix things up a bit.
You are creating a new variable that points to the beginning of the array and you pass pointer to that variable into the next function.
Which does indeed change the original variable passed, but remember, this is
pnot the array. What you did is change whereppoints. It now points to a constant"S".