saurabh
saurabh

Reputation: 121

change string to point to next character in function

#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

Answers (3)

Ed Heal
Ed Heal

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;
}

See https://ideone.com/Ouo19v

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

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

John Zwinck
John Zwinck

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

Related Questions