Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading