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.

4
  • 1
    This is wrong: w = "ab"; You need to use strcpy. Commented Nov 15, 2011 at 14:04
  • sizeof (char) is per definition always 1. So no need to write it. So incrementing a pointer can be written simply p++ Commented Nov 15, 2011 at 14:11
  • exactly, you actually got a memory leak here because you make w point away to the other place than where it is allocated Commented Nov 15, 2011 at 14:17
  • 1
    There is also a memory leak because free() isn't called anywhere... Commented Nov 15, 2011 at 14:45

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

2 Comments

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)
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. :)
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;
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.