Slaxt
Slaxt

Reputation: 53

argument list in Function pointer

I can print more than 2 arguments in my function ptr * Os_printf * but my function only works with 1 argument.

for example -->

Os_printf("Moon %d %d",55,5);

OUT:

Moon 55 5

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

char db[50];

void test_1(int (*debug)())
{
    debug("JOY %d %d \n",4,55);
}

volatile int (*ptr_fscreener)(char * __restrict, const char * __restrict, ...);

void Os_formater(int (*debug)() )
{
  ptr_fscreener=debug;
}

void Os_printf(const char  * __restrict out,void**d)
{
va_list args;
char db[50];
ptr_fscreener(db,out,d);
puts(db);
}

int main(void) {
    Os_formater(sprintf);
    Os_printf("Moon %d",55);
    test_1(printf);
    puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
    return EXIT_SUCCESS;
  }


/*******  OUTPUT For example  ******/
       Moon 55
       JOY 4 55
       !!!Hello World!!!

Upvotes: 0

Views: 393

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754590

You need to use <stdarg.h> and probably vsnprintf(), amongst numerous other changes:

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

void test_1(int (*debug)(const char *format, ...))
{
    debug("JOY %d %d\n",4,55);
}

static int (*ptr_fscreener)(char *, size_t, const char *, va_list);

void Os_formatter(int (*debug)(char *buffer, size_t buflen, const char *format, va_list args))
{
    ptr_fscreener = debug;
}

void Os_printf(const char *out, ...)
{
    va_list args;
    char db[50];
    va_start(args, out);
    ptr_fscreener(db, sizeof(db), out, args);
    va_end(args);
    puts(db);
}

int main(void)
{
    Os_formatter(vsnprintf);
    Os_printf("Moon %d",55);
    test_1(printf);
    puts("!!!Hello World!!!");
    return EXIT_SUCCESS;
}

Using vsnprintf() gives you some protection against buffer overflow as long as you use it correctly. It is fairly straight-forward to revert to using vsnprintf(); it is not possible to use snprintf() or sprintf() reliably, I think.

Compilation:

gcc -O3 -g -std=c99 -Wall -Wextra va.c -o va  

Result:

Moon 55
JOY 4 55
!!!Hello World!!!

Upvotes: 3

Related Questions