The p, n, and % conversion specifiers printf() C function program example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)
Other info: none
To do: Displaying integers using p, n and % conversion specifiers of the printf() C function
To show: How to use the p, n, and % conversion specifiers of the printf() C function in printing integers
// Using the p, n, and % conversion specifiers
#include <stdio.h>
int main(void)
{
// pointer variable
int *ptr;
int x = 12345, y = 0, z = 0;
// assigning address of variable x to variable ptr
ptr = &x;
printf("\nUsing the p, n, and %% conversion specifiers.\n");
printf("Compare the output with the source code\n");
printf("--------------------------------------------\n\n");
printf("The value of pointer ptr is %p\n", ptr);
printf("The address of variable x is %p\n\n", &x);
// By default %n is disabled because not secure. To enable it use the following function, 1 - enable, 0 - disable
y = _set_printf_count_output(1);
printf("Total characters printed on this line is: %n", &y);
printf(" y = %d\n\n", y);
y = printf("This line has 34 + NULL characters\n");
printf("%d characters were printed\n\n", y);
printf("Printing a %% in a format control string\n");
return 0;
}
Output example:
Using the p, n, and % conversion specifiers.
Compare the output with the source code
--------------------------------------------
The value of pointer ptr is 0012FF54
The address of variable x is 0012FF54
Total characters printed on this line is: y = 42
This line has 34 + NULL characters
35 characters were printed
Printing a % in a format control string
Press any key to continue . . .