0

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.

Matt
  • 22,721
  • 17
  • 71
  • 112
kejmil01
  • 95
  • 2
  • 7

3 Answers3

4

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)

ComfortablyNumb
  • 3,391
  • 2
  • 14
  • 15
  • Thank you. Problem solved, but can you explain it ? :) &w - passes adress of pointer, yes ? I cant understand what **t meaning. (sory for my english) – kejmil01 Nov 15 '11 at 14:07
  • 1
    You need to dig a bit deeper about how function call takes place. Basically, you parameter will be copied in a function, so the original one will not be changed after the call. To change it, you need manipulate its address. Here what you want to change is a pointer, so you need pass the parameter as the address of pointer: the pointer of pointer. Now can you accept my answer so that I earn some reputation. :) – ComfortablyNumb Nov 15 '11 at 14:14
1

Try this:

static char *por(char *t)
{
    return t + sizeof(char);
}

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

    return 0;
}
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
0

you are incrementing the copy which is local to the function.

Bazooka
  • 1,428
  • 4
  • 15
  • 24