Reputation: 121
#include <stdio.h>
void change(char *str)
{
(*str++);
return;
}
int main()
{
char *str = "ABC";
printf("before change %s \n",str);
change(str);
printf("after change %s \n",str);
return 0;
}
Output of the program is
ABC
ABC
I want output to be
ABC
BC
I don't want to return string, str needs to be modified in change function; return type of change function should remain void. I don't know how to do this.
I did try to google it but i didn't find the solution.
Upvotes: 0
Views: 1082
Reputation: 60017
As we are in C would you need a pointer to a pointer.
I.e
void change(char **str)
{
*str = *str + 1;
}
Then
int main()
{
char *str = "ABC";
printf("before change %s \n",str);
change(&str);
printf("after change %s \n",str);
return 0;
}
Upvotes: 0
Reputation: 726809
The expression (*str++);
increments a local copy of str
, not str
from main
. This is because C uses pass-by-value technique for function parameters.
You need to change your function to take a pointer to pointer, and pass a pointer to str
in order to achieve the desired effect.
Upvotes: 0
Reputation: 249394
In C if you want to change the value of an argument to a function, you need to take that argument by pointer. And since here you are trying to change a pointer, it needs to be a pointer to a pointer:
void change(char **str)
{
(*str)++;
}
Then:
change(&str);
Upvotes: 4