Learning C at University. This is not a homework, but I was trying to do something (some "creative" part of the assignment) and got stuck.
I understand that this is possible
printf("%d\n", printf("23.4")); // -> 23.44 (i.e. 23.4 + 4 bytes written)
but how can I use sprintf()
as first argument of printf()
?
something like :
char * getFormatString(int n) {
char * buffer;
sprintf(buffer, "Value with %%d decimals is %%.%df", n);
return buffer;
}
void foo() {
int decimals = 2;
float pi = 3.141592;
printf(getFormatString(decimals), decimals, pi); // should output "Value with 2 decimals is 3.14"
}
Is this even possible ? So far, I get a seg fault when executing it.