I had to write a function that modified a string. Because I need to modify the string my immediate thought was that I needed to pass the string as reference:
void substitution (char **str, char c1, char c2)
{
int i;
for (i=0; (*str[i])!='\0'; ++i)
if (c1 == (*str[i]))
(*str[i]) = c2;
}
However I decided to try to pass the string as value and to my surprise the program still works:
void substitution(char *str, char c1, char c2)
{
int i;
for (i=0; (str[i])!='\0'; ++i)
if (c1 == (str[i]))
(str[i]) = c2;
}
I tested my program using
int main(void)
{
char str[]="banana";
substitution(str, 'a', 'e');
printf("%s\n", str);
}
Which always returned the output "benene". I don't understand why this is happening. I thought that if I passed the string by value, the function would only change the string locally and that when I returned I would still obtain the original string.
Can someone help me clarify this?