Search code examples
cfunctionpointersfunction-pointerspointer-address

Changing pointer address - function


I have problem with pointers. This is working fine -

int main(void){
    char *w;
    w = calloc(20, sizeof(char));
    w = "ab";

    printf("%c",*w);
    w = w + sizeof(char);
    printf("%c",*w);

    return 0;
}

but if i use function like:

void por(char *t){
    t = t + sizeof(char);
}

and

int main(void){
    char *w;
    w = calloc(20, sizeof(char));
    w = "ab";
    printf("%c",*w);
    por(w);
    printf("%c",*w);

    return 0;
}

then it prints "aa" instead of "ab". I know its probably pretty stupid question, but i don't know what is going and how to solve that issue.


Solution

  • In your por function, t will not be changed. You need change it

    void por(char **t){
     *t = *t + sizeof(char);
    }
    

    and call it with por(&w)