The reason for this is because the printf()
function has been written to understand different types of arguments passed to it. The format specifier in the string tells printf()
what to expect each argument to be. Then the documentation tells you what to pass to it.
ie. basically it works because printf()
follows a defined specification, and you're following it.
So in your first example, you use the %d format. printf()
takes this to mean the argument should be an integer value. Not a pointer to an integer, but an integer. Which is why this works:
void function1(int *ptr) {
printf("%d", *ptr);
}
and this doesn't:
void function1(int *ptr) {
printf("%d", ptr);
}
Your second example is a string and there is some possibility of confusion here as strings in C are not really a direct data types (as such). They are a pointer to a character which is followed by other characters and then terminates with a NULL \0.
void function2(char *str) {
printf("%s", str);
}
Now, if strings were a data type in C, then you would probably pass them in the same way you do other values (this is purely hypothetical):
void function2(string str) {
printf("%s", str);
}
So in summary:
%d -> int
%s -> char *