Search code examples
cpointerspass-by-referencepass-by-valuefunction-definition

How to increment "char *" inside a function without returning it?


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?


Solution

  • 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);