I'm trying to use a variable to set a somewhat dynamic field width in a printf() format specifier. I searched the site and found the following which seemed to be just the help that I need.
Set variable text column width in printf
When I use "%*1$d%*2$s" I get the following error.
ex8_3.c:29:11: warning: missing $ operand number in format [-Wformat=]
29 | printf("The value entered, in characters, was \"%*1$d%*2$s\".\n", fieldWidth, string);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
However, when I use "%1$*d%2$*s" I get the following error.
ex8_3.c: In function ‘main’:
ex8_3.c:29:4: warning: missing $ operand number in format [-Wformat=]
29 | printf("The value entered, in characters, was \"%1$*d%2$*s\".\n", fieldWidth, string);
| ^~~~~~
Note the different locations of the asterisks in both statements. The second version seems to be the "more correct" one, according to the compiler. What I don't understand, in both cases, is the "missing $ operand number" referred to in the error messages. The printf() uses two variables and I have provided two instances of "$ operand number". Given the examples in the web page linked to above, I just don't see what I am doing wrong/not understanding. Could someone please explain what the error messages are referring to and what corrections I need to implement ?
Here is the code in question.
int main(void)
{
int number = 0; // Value supplied by user.
int arraySize; // Size of the digit array.
int fieldWidth = 0; // Allow variable field width in printf().
number = readValue(); // Read in value from user.
arraySize = countDigits(number) + 2; // Get array size.
fieldWidth = arraySize + 2; // Set variable field width for printf().
char string[arraySize]; // Define array to hold digit characters.
itoa(number, string); // Convert value to string.
printf("The value entered, in characters, was \"%1$*d%2$*s\".\n", fieldWidth, string);
return 0;
}
Here is the command line in use.
gcc ex8_3.c -Wall -std=c11 -ggdb -o ex8_3