简体   繁体   中英

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.

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)

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

您正在增加该功能本地的副本。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM