Noktua Noktua - 4 days ago 5
C Question

How to convert int to char[] with sprintf() if char is pointer and the int not?

I likely don't understand the

sprintf
function.

char s[30];
int i;

scanf("%d",&i);
sprintf(s,i); /*->warning: makes pointer from int*/

Answer

sprintf accepts the target char[] as the first argument, and the rest of the arguments are the same as printf, or scanf's (format string first, then additional args if present).

So, in your case, it would simply be:

char s[30];
int i;

scanf("%d",&i);
sprintf(s, "%d", i);

For an input of 3, s would become '3'.

With sprintf(s, "%d%d", i, i);, it would become '33'.

The reason it tried to interpret i as a pointer in your example, was that it expected a (char) pointer (the format string).

Comments