Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to be "terminated by a zero"?

Tags:

c++

c

string

I am getting into C/C++ and a lot of terms are popping up unfamiliar to me. One of them is a variable or pointer that is terminated by a zero. What does it mean for a space in memory to be terminated by a zero?

like image 422
numerical25 Avatar asked Apr 19 '10 13:04

numerical25


People also ask

What is a zero terminated array?

In computer programming, a null-terminated string is a character string stored as an array containing the characters and terminated with a null character (a character with a value of zero, called NUL in this article).

Why do string subscripts ends with null character?

The end of the character string or the NULL byte is represented by '0' or '\0' or simply NULL. The NULL character doesn't have any designated symbol associated with it and also it is not required consequently. That's the major reason it is used as a string terminator.

How do you find the length of a null-terminated string?

strlen(s) returns the length of null-terminated string s. The length does not count the null character.


1 Answers

Take the string Hi in ASCII. Its simplest representation in memory is two bytes:

0x48
0x69

But where does that piece of memory end? Unless you're also prepared to pass around the number of bytes in the string, you don't know - pieces of memory don't intrinsically have a length.

So C has a standard that strings end with a zero byte, also known as a NUL character:

0x48
0x69
0x00

The string is now unambiguously two characters long, because there are two characters before the NUL.

like image 182
RichieHindle Avatar answered Oct 06 '22 01:10

RichieHindle