How does printf display a string from a char*?
Solution 1
*letter
is actually a character; it's the first character that letter
points to. If you're operating on a whole string of characters, then by convention, functions will look at that character, and the next one, etc, until they see a zero ('\0') byte.
In general, if you have a pointer to a bunch of elements (i.e., an array), then the pointer points to the first element, and somehow any code operating on that bunch of elements needs to know how many there are. For char*
, there's the zero convention; for other kinds of arrays, you often have to pass the length as another parameter.
Solution 2
Simply because printf has a signature like this: int printf(const char* format, ...);
which means it is expecting pointer(s) to a char table, which it will internally dereference.
Solution 3
%s
prints up to the first \0
see: http://msdn.microsoft.com/en-us/library/hf4y5e3w.aspx, %s
is a character string format field, there is nothing strange going on here.
Solution 4
printf("%s")
expect the address in order to go through the memory searching for NULL
(\0
) = end of string. In this case you say only letter
. To printf("%c")
would expect the value not the address: printf("%c", *letter);
Solution 5
letter does not point to the string as a whole, but to the first character of the string, hence a char pointer.
When you dereference the pointer (with *
) then you are referring to the first character of the string.
however a single character is much use to prinf (when print a string) so it instead takes the pointer to the first element and increments it's value printing out the dereference values until the null character is found '\0'.
As this is a C++ question it is also important to note that you should really store strings as the safe encapulated type std::string
and you the type safe iostreams where possible:
std::string line="hi how r u";
std::cout << line << std::endl;
Naruto
Updated on April 25, 2020Comments
-
Naruto about 4 years
Consider a simple example
Eg: const char* letter = "hi how r u";
letter is a const character pointer, which points to the string "hi how r u". Now when i want to print the data or to access the data I should use
*letter
correct?But in this situation, shouldn't I only have to use the address in the call to printf?
printf("%s",letter);
So why is this?