Can someone explain why this outputs garbage values?

Dustin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Dec 9 15:28:43 PST 2014


On Tuesday, 9 December 2014 at 20:24:18 UTC, Adam D. Ruppe wrote:
> Also, the reason why the special function is needed is that the 
> argptr is just a pointer to the arguments. If you pass that to 
> printf, how does it know that there's varargs on the other end 
> instead of just being another pointer whose numeric value it is 
> supposed to print out?

I got it to work with vsnprintf with the following code:
___________________________________________________
import core.vararg;
import std.string : toStringz;
import std.c.stdio : printf;

char[256] buffer;

extern(C) void vsnprintf(char* s, ulong n, const(char*) format, 
va_list arg);

void print(string fmt, ...)
{
	char* dest = buffer.ptr;

	va_list list;
	va_start(list, fmt);
	vsnprintf(dest, 256UL, toStringz(fmt), list);
	printf(dest);
}

void main(string[] args)
{
	print("%d, %d, %d\n", 1, 2, 3);
}
___________________________________________________

I did have to declare my own function prototype because importing 
vsnprintf from std.c.stdio produced the following error: 
"test.d(13): Error: function core.stdc.stdio._vsnprintf (char* s, 
ulong n, const(char*) format, __va_list_tag* arg) is not callable 
using argument types (char*, ulong, immutable(char)*, char*)"

It works fine with my own function declaration though...
(I'm using LDC on Win64)


More information about the Digitalmars-d-learn mailing list