Reply with “Embedded Base” to get more learning materials for free
When writing code, we assign an initial value to variables to prevent uncertainty in their initial values due to the <span>compiler</span>
. For numeric type variables, they are often initialized to 0, but how should other types of variables, such as <span>char</span>
, <span>pointer</span>
, etc., be initialized?
Initialization of Numeric Variables
Integer and floating-point variables can be initialized at the time of definition, generally initialized to <span>0</span>
.<span>1</span><span>int</span> inum = <span>0</span>;<span>2</span><span>float</span> fnum = <span>0.00f</span>;<span>3</span><span>double</span> dnum = <span>0.00</span>;
Initialization of Character Variables
Character variables can also be initialized at the time of definition, generally initialized to <span>'\0'</span>
.<span>1</span><span>char</span> ch = <span>'\0'</span>;
String Initialization
There are many methods for string initialization; I will briefly introduce three. Since a string is essentially an array of characters, the ultimate goal of its initialization is to initialize each character in the character array to '\0'
.
Method 1: Use an empty string
<span>""</span>
.
char str[10] = “”;
Method 2: Use
<span>memset</span>
.
char str[10];memset(str, 0, sizeof(str));
Method 3: Write a loop.
char str[10];for(int i = 0; i < 10; i++){ str[i] = ‘\0’;}The second initialization method is recommended, which is to use <span>memset</span>
for initialization.
Many people have a vague understanding of the
<span>memset</span>
function, knowing that it can initialize many types of variables but not understanding its principle. Here is a brief explanation:memset
fills by bytes. First, look at the following code:
int num;memset(&num, 0, sizeof(int));printf(“step1=%d\n”, num);memset(&num, 1, sizeof(int));printf(“step2=%d\n”, num);
Before discussing, let’s look at the output results
chenyc@DESKTOP-IU8FEL6:~/src$ gcc -o memset memset.c -gchenyc@DESKTOP-IU8FEL6:~/src$ ./memsetstep1 = 0step2 = 16843009chenyc@DESKTOP-IU8FEL6:~/src$
Seeing this output, is it different from what you imagined?
<span>step1 = 0</span>
is understandable, but <span>step2 = 16843009</span>
is confusing for many. According to common sense, shouldn’t it be <span>= 1</span>
? This is what I want to say: memset fills by bytes. We know that <span>int</span>
is 4 bytes (each byte has 8 bits), represented in binary as:00000000 00000000 00000000 00000000
According to the principle of byte filling, the result of step1 is that all 4 bytes are filled with 0, so the result remains 0:
00000000 00000000 00000000 00000000
While step2 fills each byte with 1 (note that it is each byte, not each bit), so the corresponding result should be:
00000001 00000001 00000001 00000001
Everyone can convert the above binary number to decimal and see if it is
<span>16843009</span>
. So strictly speaking, the memset function itself does not have the function of initialization; it is purely a byte-filling function, and people have extended its use to initialization.
There is a small trick in string initialization. We know that a string is essentially a character array, so it has two characteristics:
- The string is continuous in memory,
- The string ends with
<span>'\0'</span><span>. Therefore, when initializing, we always prefer to allocate memory with a length of the string plus 1.</span>
char year[4+1];memset(year, 0, sizeof(year));strcpy(year,“2018”);
Pointer Initialization
Generally, pointers are initialized to <span>NULL</span>
.int *pnum = NULL;int num = 0;pnum = #Pointers are both loved and hated. Generally, integers, strings, etc., can be used directly after initialization, but if a pointer is initialized to <span>NULL</span>
and not allocated memory for that pointer, it can lead to unpredictable errors (the most common is a segmentation fault caused by dereferencing a null pointer).In dynamic memory management, since the memory for variables is allocated on the heap, functions like <span>malloc</span>
, <span>calloc</span>
, etc., are used to request dynamic memory, and after use, it needs to be released promptly. After releasing dynamic memory, the pointer should be set to null, which is often overlooked.char *p = NULL; p=(char *)malloc(100); if(NULL == p){ printf(“Memory Allocated at: %x\n”,p); }else{ printf(“Not Enough Memory!\n”); } free(p); p = NULL; // This line to set the pointer to null is essential; otherwise, it is likely to operate on this wild pointer unknowingly, leading to serious issues.Many people often make a mistake. We know that when a pointer is passed as an argument, it degenerates into an array, so many think of using <span>memset</span>
to initialize that pointer:void fun(char *pstr){ memset(pstr, 0, sizeof(pstr)); …}This writing is incorrect. Regardless of whether pointers can be initialized with <span>memset</span>
, pointers first store a 4-byte address, so <span>sizeof(pstr)</span>
will always be <span>= 4</span>
, making such initialization meaningless.
Structure Initialization
Structure initialization is relatively simple, generally using <span>memset</span>
method.typedef struct student{ int id; char name[20]; char sex;}STU;STU stu1;memset((char *)&stu1, 0, sizeof(stu1));Regarding the length issue of initializing structures, that is, the third parameter of <span>memset</span>
, generally, passing the data type and variable name has the same effect. In the above example, the following writing is equivalent:memset((char *)&stu1, 0, sizeof(STU));However, for initializing arrays of structures, the length needs to be noted. Using the above example for illustration:STU stus[10];memset((char *)&stus, 0, sizeof(stus)); // Correct, the array itself is continuous in memory, so sizeof gives the byte length of the array.memset((char *)&stus, 0, sizeof(STU)); // Incorrect, only the first STU structure is initialized, and the other 9 STU elements are not initialized.memset((char *)&stus, 0, sizeof(STU)*10); // Correct, the effect is the same as the first one.Some people habitually write the second parameter of <span>memset</span>
in the following form:memset((char *)&stu1, 0x00, sizeof(stu1));As long as you understand that <span>memset</span>
fills by bytes, you will know that this writing is also correct and has no issues.
Disclaimer: The content of this article is sourced from the internet, and the copyright belongs to the original author. If there are any copyright issues, please contact for removal.
Recommended Reading
-
Advanced Usage of Embedded C Language
-
Importing Keil Projects into VSCode Development
-
Electrical Competition – Gain Controllable RF Amplifier
-
Electrical Competition – Bidirectional DC-DC Converter
-
Electrical Competition – Wind Power Swing Control System
-
Electrical Competition – Indoor Visible Light Positioning Device
-
Quadrotor Autonomous Flight Detection and Tracking System
-
Electrical Competition – Cricket Control System
-
30 Lines of Code to Automatically Steal Energy from Ant Forest
-
Electrical Competition – Microgrid Simulation System
-
Step-by-Step Guide to Embedded C Language Optimization Techniques
-
Comprehensive Summary of Basic Knowledge of Embedded Systems (Part 2)!
-
Comprehensive Summary of Basic Knowledge of Embedded Systems (Part 1)!