Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does printf display a string from a char*?

Tags:

c++

char

pointers

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?

like image 587
Naruto Avatar asked Sep 16 '25 19:09

Naruto


2 Answers

*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.

like image 75
Ernest Friedman-Hill Avatar answered Sep 19 '25 09:09

Ernest Friedman-Hill


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.

like image 32
teukkam Avatar answered Sep 19 '25 09:09

teukkam