user1698144
user1698144

Reputation: 764

Why is vsprintf only operating on the first character

The code below returns the following:

Input was: 6789
Vsprintf Buffer: 54

Why is the vsprintf buffer only returning 54?

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

void vout(char *string, char *fmt, ...);
char fmt1 [] = "%d";

int main(void)
{
   char string[32];
   char *xy = "6789";

   vout(string, fmt1, * xy);
   printf("Input was: %s\n", xy);
   printf("Vsprintf Buffer:  %s\n",string);
}

void vout(char *string, char *fmt, ...)
{
   va_list arg_ptr;

   va_start(arg_ptr, fmt);
   vsprintf(string, fmt, arg_ptr);
   va_end(arg_ptr);
}

Upvotes: 0

Views: 108

Answers (2)

id01
id01

Reputation: 1597

vsprintf() reads fmt from arg_ptr and prints to string. This will not work, as it will take the first 32-bit memory block, in this case, containing the ascii character '6', and write it as an integer to string. Use vsscanf instead.

vsscanf(string, fmt, arg_ptr);

Upvotes: 0

Chris Dodd
Chris Dodd

Reputation: 126408

You're passing a single character '6' and printing it with the format%d, so it prints the character code as an integer -- 54.

Upvotes: 1

Related Questions