MasterMastic
MasterMastic

Reputation: 21286

How does printf know the length of the format argument?

int printf (const char* format, ... );

This is the signature of printf. What I don't understand is, how does printf know the length of the first argument (the const char* format).

It knows the start (because it's a pointer, I get that), but pointers don't have an end or something. Usually when you want to print something you must give a length (For example, Linux's sys_write) so how does printf know?

Edit:

I've been looking through the code I wrote in ASM a little more and I think it just looks for a \0 char. Is that correct?

Upvotes: 5

Views: 1542

Answers (3)

MSalters
MSalters

Reputation: 179917

It doesn't know. Try printf("Hello \0 World\n");. printf doesn't know that that string contains 15 characters.

Upvotes: 0

user2180519
user2180519

Reputation:

When a string is properly declared there is always a NULL (\0) value at the end of it, that marker is used to mark the end of the string for all these printing functions. If it is omitted (difficult to do in most cases) the printing function will just keep printing memory until it runs into a 0 value in memory.

"Anything" is a char array that ends with i n g \0

Edit: '\0' == 0 and '0' != 0

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318518

It is a null-terminated string (like all strings in C), so the first ASCII NUL ('\0' or plain 0) byte indicates the end of the string.

If you have a string "meow" in C it actually uses 5 bytes of memory which look like this in memory. The \0 is obviously a single byte with the value 0.

meow\0

In case you wonder how an actual '0' digit would be represented: The numbers 0..9 have the ASCII values 48..57, so "me0w" would have 48 byte at its third position.

Upvotes: 12

Related Questions