I seem to be having a problem with sprintf, the compiler gives me an error.

char* title = sprintf("%03d.jpg", counter);

The above gives me the following response in the compiler:

recover.c:39:39: error: incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *' [-Werror,-Wint-conversion]
char* title = sprintf("%03d.jpg", counter);

Does sprintf not take the same formatting arguments as printf? Or am I doing something else wrong?


See the man page for sprintf here: https://reference.cs50.net/stdio.h/sprintf

The function takes two arguments. This particular call to sprintf requires a third because the format has a variable in the form of %03d. You're missing the first argument which is to represent the char* to which sprintf writes.

The example on CS50 Reference should help.

  • Thank you! I'd totally missed that. – Fobok Feb 10 '16 at 21:44

You're doing something else wrong. While you want to put a string into title, you're actually trying to put the return value from sprintf() into title and to put the contents of counter into a constant string surrounded by double quotes.

The first parameter should be the string variable that you're trying to put the string in. The second (your first) parameter is the formatting string, and in this case, subsequent parameters map to placeholders in the format string, just like in printf. Your code should look something like this:

`sprintf(title,"%03d.jpg", counter);`
  • I wish I could 'accept' both answers as you both answered within a few seconds of each other, but I accepted Peter because he got there a few seconds earlier and I'd just figured it out from what he commented. But I did upvote both :) – Fobok Feb 10 '16 at 21:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .