%0*d format not supported in sprintf?

First, let me state that I'm a real newb to C so I apologize in advance if I'm asking dumb questions..

I'm trying to create a padding function for padding numbers with 0's to specified width and I found that one of the formats specified by printf is a * to indicate that the first parameter is actually the length of the padding however this does not work in practice as it always returns a 0 length string when I try to use it. So, my first question is, does anyone know why? ex: sprintf(buf, "%*d", 3, 7) should return "007" but returns "" instead.

I tried to come up with my own method of accomplishing this but my lack of C knowledge caused me to come up with what seems to me like a very lacking solution:

char * pad( int number, char width ) {
  static char buf[6];
  char params[5];
  params[0] = '%';
  params[1] = '0';
  params[2] = width;
  params[3] = 'd';
  params[4] = '\0';
  sprintf(buf, params, number);

  return buf;
}

I assume there must be a better way of doing this? The first issue is that I shouldn't have to pass the width as a char, but I could not find a way to convert a byte to a char, at least not a short hand method that would work without adding more lines of code. I'm also limited to only padding up to 9 chars which I will never need more of but it drives me nuts that I've coded in a limitation.

Any help with his is HUGELY appreciated!!

Why not use two sprintf calls?

char format[6];
sprintf(format, "%%0%dd", width);

sprintf(buf, format, number);

I think that the %% is right to get the % in the output string, but I could be wrong.

Thanks PaulS! Man, I feel like an idiot for not thinking of that myself... I think I need to go to bed now!..lol

works perfectly btw!

Man, I feel like an idiot for not thinking of that myself.

Don't. Sometimes it's hard to see the forest for all the trees. Someone else looks at the scene for 30 seconds and says 'lovely forest", while your busy struggling with all the trees.

It's documented on my page here: Gammon Forum : Electronics : Microprocessors : Arduino programming traps, tips and style guide