SoFunction
Updated on 2025-04-14

Initialization method of various variables in C language

Numerical variable initialization

Integer and floating-point variables can be initialized while they are defined, and are generally initialized to0

    int  inum  = 0;
    float fnum = 0.00f;
    double  dnum = 0.00;

Character variable initialization

Character variables can also be initialized at the same time as defined, usually initialized to'\0'

char ch = '\0';  

String initialization

There are many methods for initializing strings. I will briefly introduce three types here. Because strings are essentially character arrays composed of characters, the ultimate purpose of initialization.It is to initialize the characters in the character array into'\0'

Method 1:Use empty string""

char str[10] = "";

Method 2:usememset

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 here. That is to usememsetInitialize.

Many people are rightmemsetThis function has only a little understanding. It only knows that it can initialize many data type variables, but it does not know what its principle is. Here is a brief explanation:memsetIt is padded in bytes.

Let's 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 take a look at the results of the operation

chenyc@DESKTOP-IU8FEL6:~/src$ gcc -o memset  -g
chenyc@DESKTOP-IU8FEL6:~/src$ ./memset
step1 = 0
step2 = 16843009
chenyc@DESKTOP-IU8FEL6:~/src$

Is this running result different from what you imagined?
step1 = 0I believe everyone can understand it, butstep2 = 16843009Many people can't understand it. According to general inertial thinking, it should not be= 1Is that right?

That's what I'm going to sayMemset is padded by bytes.

We know,intThe type is 4 bytes (each byte has 8 bits), and it should be expressed in binary:

00000000 00000000 00000000 00000000

According to the principle of byte padding, the result of step1 is to fill all 4 bytes with 0, so the result is still 0:

00000000 00000000 00000000 00000000 

step2 fills each byte with 1 (note that it is each byte, not every byte bit), so the corresponding result should be:

00000001 00000001 00000001 00000001

You can convert the binary number above to decimal to see if it is16843009

So strictly speaking, the memset function itself does not have the function of initialization, but is a simple function of byte fill, but people have expanded the function of initialization during the use.

There is a little trick to initialize strings, we know that strings are essentially character arrays, so it has two characteristics,

  • Strings are continuous in memory.
  • String encounter'\0'Finish.
    So when we initialize, we are always willing to initialize the memory of the length of the string itself by 1.
char year[4+1];
memset(year, 0, sizeof(year));
strcpy(year,"2018");

Pointer initialization

Generally speaking, pointers are initialized toNULL

int *pnum = NULL;
int num = 0;
pnum = &num;

Pointers are something that makes people love and hate. They are generally plastic surgery, strings, etc., and can be used directly after initialization. However, if the pointer is initialized,NULLAfter that, if the pointer is not reallocated memory, unpredictable errors will occur (the most common one is the segfault caused by operating a null pointer).

In dynamic memory management, since the memory of variables is allocated in the heap, it is generally usedmalloccallocIf the function has applied for dynamic memory, it needs to be released in time after use. Generally, the pointer must be empty in time after the dynamic memory is released, which is also easy for many people to ignore.

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 is essential to empty the pointer,Otherwise, it is very likely that this wild pointer was later operated without knowing it,This leads to serious problems

A mistake that many people often make. We know that when a pointer is passed as a real parameter, the pointer has degenerated into an array, so many people think of using it.memsetTo initialize the pointer:

void fun(char *pstr)
{
  memset(pstr, 0, sizeof(pstr));
  ...
}

This is incorrect. Let's just ignore whether the pointer can be used or notmemsetTo initialize, the pointer first saves a 4-byte address, sosizeof(pstr)Only forever= 4, such initialization is meaningless.

Structure initialization

The initialization of the structure is relatively simple, and it is basically usedmemsetway.

typedef struct student
{
    int id;
    char name[20];
    char sex;
}STU;
STU stu1;
memset((char *)&stu1, 0, sizeof(stu1));

Regarding the length of the initialization structure, that is,memsetThe third parameter of , generally speaking, the effect of the incoming data type and variable name is the same. In the above example, the following is the equivalent effect:

memset((char *)&stu1, 0, sizeof(STU));

However, when it comes to initializing the structure array, you need to pay attention to the length. Let’s explain it as follows:

STU stus[10];
memset((char *)&amp;stus, 0, sizeof(stus)); //Correct, the array itself is continuous in memory, and the sizeof takes out the byte length of the arraymemset((char *)&amp;stus, 0, sizeof(STU));  //Error, only the first STU structure will be initialized, and there are 9 STU elements that are not initialized afterwards.memset((char *)&amp;stus, 0, sizeof(STU)*10);  //correct,The effect is the same as the first one

Some people are used tomemsetThe second parameter of the following:

memset((char *)&stu1, 0x00, sizeof(stu1));

As long as you understandmemsetIt is filled in bytes, so you know that writing this way is correct, and there is no problem at all.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.