更改指针地址 - 函数

发布于 2024-12-15 18:55:23 字数 553 浏览 5 评论 0原文

我的指针有问题。 这工作正常 -

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

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

    return 0;
}

但如果我使用如下函数:

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

然后

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

    return 0;
}

它会打印“aa”而不是“ab”。 我知道这可能是一个非常愚蠢的问题,但我不知道发生了什么以及如何解决该问题。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

方觉久 2024-12-22 18:55:23

在您的 por 函数中, t 不会改变。您需要更改它

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

并使用 por(&w) 调用它

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)

橙味迷妹 2024-12-22 18:55:23

试试这个:

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

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;
}
百变从容 2024-12-22 18:55:23

您正在增加函数本地的副本。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文