Home > front end >  How to increment "char *" inside a function without returning it?
How to increment "char *" inside a function without returning it?

Time:03-28

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?

CodePudding user response:

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