Search code examples
cwarnings

Passing Argument 1 makes integer from pointer without a cast warning for putchar


I'm studying an exercise of making a simple code that has the function that acts the same way as printf using a variadic function.

Also, I wish to use sprintf and putchar, and not printf.

The code seems to act and give the results as it should do (i.e print a character for %c, and an integer for %d).

However, I keep getting a warning message for putchar(cStr); that says Passing Argument 1 of 'putchar' makes integer from pointer without a cast.

Also, I get a note that says expected int but argument is of type char *.

I've tried to get this solved by changing putchar(cStr); into putchar(*cStr);, but then the code gives me a segment fault.

What should I do to get the warning message and note solved?

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

void new_printf(const char*format, ...);

int main(void)
{
    new_printf("A single character : %c An integer : %d \n", 'T', 37);
    return 0;
}

void new_printf(const char *format, ...)
{
    va_list ap;
    char ary[50];
    char *cStr;
    int iNum, i=0;
    va_start(ap, format);
    while(*format)
    { 
        if(strncmp(format, "%d",2) == 0){
            iNum = va_arg(ap, int);
            sprintf(ary, "%d", iNum);
            while(ary[i]!='\0'){
                putchar(ary[i]);
                i++;
            }       
            format = format + 2;
        }
        else if(strncmp(format, "%c", 2)==0)
        {
            cStr = va_arg(ap, char*);
            putchar(cStr);
            format = format + 2;
        }
        else{
            putchar(*format);
            format++;
        }
    }
    va_end(ap);
}

The correct results would be as follows:

A single character : T An integer : 37

Solution

  • In the call new_printf("A single character : %c An integer : %d \n", 'T', 37);, 'T' is passed for the %c conversion. 'T' is a character: It is a small integer value. It is not a pointer. For historic reasons, its type is int. This is a correct thing to pass for %c.

    Under else if(strncmp(format, "%c", 2)==0), in cStr = va_arg(ap, char*);, you tell va_arg to give you the next argument and that that argument is a char *. It is not. It is an int.

    You should retrieve it with va_arg as an int and assign it to an int, not to char *, or simply use it directly as an int.

    You should use int x = va_arg(ap, int); putchar(x); or simply putchar(va_arg(ap, int));.