Site Search

Hello. It's guu.

Until the other day, I was studying C language hard in training.

 

A few days after studying C language, I encountered something mysterious.

It's "NULL". The name is too suspicious...

 

I looked up NULL and found the following:

"It is a type of data representation in programming languages and databases,

A state that does not contain any data, or an empty string of length 0.”

 

A state in which no data is included … do we need to express it?

I couldn't help but have such doubts.

However, as I proceeded with the training, I gradually understood the importance of NULL .

 

Today I tried to summarize the episode that I learned the importance of such NULL.

Commentary

Suppose you store the string "hello" (5 characters) in an array with 80 elements ( str[80] ).

char str[80] = “ hello ” ; /*サンプルコード */

And output the string stored in the array ( str[80] ) with the code below.

printf ( “ % s ” , str );

The array has 80 elements (boxes of characters) and 5 characters stored.

Now how will the string be printed?

 

1. hello (end)

2. hello + (blank × 75 )

 

The correct answer is 1.

hello /* 出力結果 */

You know this without even thinking about it.

It's so obvious, why would you ask such a question? Some people think.

 

Here is one shocking fact.

Actually the printf() function only knows where the string starts.

 

What does this mean...

When you want to print "hello", you know where the "h" that starts the output is

We don't know the position of the output goal ' o '.

This means that the output doesn't stop after printing the characters hello .

So, the answer to the previous question would be "2 . hello + (blank x 75)"?

Do not you think so?

 

Why is the output just " hello "?

The point of this problem is "NULL"!

"NULL" is automatically put at the end of the string when you store the string in an array.

And NULL tells us the end of the string.

(The string ends when it reaches NULL )

As a result, when I printed a string with the printf () function, it only displayed the characters I stored!

Summary

A NULL is stored at the end of the string to indicate the end of the string.

Guu's tweet

I thought NULL had no presence, but in reality, he was playing a big role in a hidden place.

supplement

Strictly speaking, NULL characters are stored at the end of strings by the compiler when you compile a program containing strings.

* Compilation is the process of translating human-written program code so that it can be read by a computer, and a compiler is something that translates (= interpreter).