Home > front end >  Sprintf() cannot accept function parameter
Sprintf() cannot accept function parameter

Time:02-22

I want to write a program like this to let sprintf() accept the function parameter

int x (char z) { //z is a character array
    float y = 10.254;
    sprintf (z, "%2.1f", y);
    printf ("%c", &z);
}

However when I enter the array as a parameter, nothing happens.

How can I let sprintf accept an external parameter

CodePudding user response:

char z is just a single character. nothing more

char* z is usually understood to be a string or a buffer capable of holding a string (or more precisely, a pointer to a character)

%c is the format specifier for a single char. %s is for a null terminated char array (or char*)

This is closer to what you want:

int x (char* z) { 
    float y = 10.254;
    sprintf (z, "%2.1f", y);
    printf ("%s", z);
}

Then invoke:

char buffer[100]; // big enough
x(buffer);
  • Related