如何增加“ char *” *&quot在功能中没有返回?

发布于 2025-01-17 14:41:49 字数 864 浏览 3 评论 0原文

我有这样的东西(简化):

void count(char *fmt)
{
    while (*fmt != 'i')
    {
        fmt++;
    }
    printf("%c %p\n", *fmt, fmt);
}

int main(void)
{
    char *a = "do something";
    char *format;

    format = a;
    printf("%c %p\n", *format, format);
    count(format);
    printf("%c %p", *format, format);
}

给出:

d 0x100003f8b
i 0x100003f94
d 0x100003f8b%   

使其工作的唯一方法是这样做:

char *count(char *fmt)
{
    while (*fmt != 'i')
    {
        fmt++;
    }
    printf("%c %p\n", *fmt, fmt);
    return (fmt);
}

int main(void)
{
    char *a = "do something";
    char *format;

    format = a;
    printf("%c %p\n", *format, format);
    format = count(format);
    printf("%c %p", *format, format);
}

但是我真的不想要这个,因为我的计数函数已经返回了我需要的值。我可以做什么来增加函数内部的格式而不返回它?

I have something like this (simplified):

void count(char *fmt)
{
    while (*fmt != 'i')
    {
        fmt++;
    }
    printf("%c %p\n", *fmt, fmt);
}

int main(void)
{
    char *a = "do something";
    char *format;

    format = a;
    printf("%c %p\n", *format, format);
    count(format);
    printf("%c %p", *format, format);
}

Gives:

d 0x100003f8b
i 0x100003f94
d 0x100003f8b%   

Only way to make it work is by doing:

char *count(char *fmt)
{
    while (*fmt != 'i')
    {
        fmt++;
    }
    printf("%c %p\n", *fmt, fmt);
    return (fmt);
}

int main(void)
{
    char *a = "do something";
    char *format;

    format = a;
    printf("%c %p\n", *format, format);
    format = count(format);
    printf("%c %p", *format, format);
}

But I really don't want this since my count function is already returning a value that I need. What can I do to increment format inside the function without returning it?

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

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

发布评论

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

评论(1

無處可尋 2025-01-24 14:41:50

通过引用将指针传递给函数。
在 C 中,通过引用传递意味着通过指向对象的指针间接传递对象。因此,取消引用指针后,您将可以直接访问原始对象并可以更改它。

例如

void count(char **fmt)
{
    while ( **fmt != 'i')
    {
        ++*fmt;
    }
    printf("%c %p\n", **fmt, *fmt);
}

并调用如下函数

count( &format);

Pass the pointer to the function by reference.
In C passing by reference means passing an object indirectly through a pointer to it. So dereferencing the pointer you will have a direct access to the original object and can change it.

For example

void count(char **fmt)
{
    while ( **fmt != 'i')
    {
        ++*fmt;
    }
    printf("%c %p\n", **fmt, *fmt);
}

and call the function like

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