Reputation: 2117
void say(char msg[])
{ // using pointer to print out the first char of string
printf("%c\n", *msg);
}
void say(char msg[])
{ // using pointer to print out the memory address of the first char of string
printf("%p\n", msg);
}
void say(char msg[])
{ // using pointer to print out the whole string
printf("%s\n", msg);
}
The first two make sense, but I don't quite understand how the third function works. All I know is that msg points to the memory address of the first character of the string. Thanks in advance.
Upvotes: 3
Views: 6751
Reputation: 1
%P prints out the stack value address pushed with the variable called. for example if value a is stored at an address 2000. and we do %P in printf() statement, the output is the address pushed into stack of the function. a's address would be pushed into stack, when we do printf("%P",a); it prints the stack's value pushed.
Upvotes: 0
Reputation: 2886
The last statement expects String because format specifier is %s . It takes base address of msg as starting address and print all characters until it reaches '\0' because string is a null terminated character array.
Upvotes: 0
Reputation: 56809
Since a C string is terminated by NUL character \0
, the printf
function will take that assumption and use the address in the pointer to print out all character until NUL character \0
is found.
If the char
array passed in is not NUL terminated, your program may crash since it may not find the NUL character and will output rubbish until it hits an unallocated memory location.
Upvotes: 3
Reputation: 61910
%s
will interpret the address of msg
as the base addresss of a C string, which is a NULL terminated ('\0'
) sequence of bytes, and therefore the printf with the %s
will take the base address of msg
and print the character equivalent of each byte starting from msg
and proceeding until it does not encounter a NULL character.
Upvotes: 5
Reputation: 518
Last one prints string.. it starts at memory address of msg and goes until it reaches termination character '\0'
Upvotes: 3