Hello. My name is Guu.
Until the other day, I was studying the C language intensively in a training program.
One day, after a few days of studying the C language, I came across something I didn't understand.
It was "NULL". The name was too suspicious....
I looked up NULL and found the following explanation.
It is a type of data representation in programming languages and databases,
It is an empty string that contains no data or a zero-length string.
No data ... why bother to represent it?
I couldn't help but ask myself such a question.
However, as the training progressed, I gradually came to understand the importance of NULLs.
Today, I would like to summarize the episode in which I learned the importance of NULL.
Explanation
Suppose we store the string "hello" (5 characters) in an array (str[80]) with 80 elements.
char str[80] = "hello"; /*sample code */
Then, the string stored in the array ( str[80] ) is output with the following code.
printf("%s", str);
The number of array elements (boxes that contain characters) is 80, and the number of stored characters is 5.
Now, how would the string be output?
- hello (end)
- hello + (spaces × 75)
The correct answer is 1.
hello /* output result */
You don't have to think about this, do you?
It is so obvious that some of you may wonder why I am asking this question.
Here's a shocking fact.
Actually, the printf () function only knows where the string starts from.
What this means is...
If you want to print "hello," you know where the output starts, "h," but you don't know where the goal of the output, "o," is.
In other words, the output does not stop after the "hello" character is printed.
So, the answer to the previous question is "2 . hello + (space x 75)"?
Don't you think?
Why is the output only "hello"?
The key to this problem is NULL!
When you store a string in an array, "NULL" is automatically placed at the end of the string.
|
And NULL tells you the end of the string. (When NULL is reached, it means the string is over.) |
|
This means that when you print out a string with the printf () function, only the characters stored in the string are displayed!
Conclusion
NULL is stored at the end of the string to indicate the end of the string.
Guu's tweet
NULL, which I thought had no presence, is actually very useful in invisible places.
Supplementation
Strictly speaking, the NULL character is stored at the end of a string by the compiler when a program containing the string is compiled.
*Compilation is the translation of program code written by a person into a computer-readable form, and the compiler is the one that does the translation (i.e., the translator).
New Engineer's Blush Blog Articles