PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 4, 2022

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

 July 04, 2022     c, function-definition, pass-by-reference, pass-by-value, pointers     No comments   

Issue

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


Answered By - Vlad from Moscow
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing