Today, I encountered a problem of global array and partial array in C language. After a long time, I did not see the problem immediately. Now I will sort out the problem and provide a solution.
Problem description:
Arrays declared globally have different effects than those declared locally.
First, let's look at a program:
Copy codeThe Code is as follows: # include <stdio. h>
# Include <stdlib. h>
# Define MAX 10
Char a [MAX];
Int main ()
{
Int I;
Char B [MAX];
Char * c = (char *) malloc (MAX * sizeof (char ));
Printf ("\ nArray a: \ n ");
For (I = 0; I <MAX; I ++)
Printf ("% d", a [I]);
Printf ("\ nArray B: \ n ");
For (I = 0; I <MAX; I ++)
Printf ("% d", B [I]);
Printf ("\ nArray c: \ n ");
For (I = 0; I <MAX; I ++)
Printf ("% d", c [I]);
Printf ("\ nDone ");
Free (c );
Return 1;
}
Compile the running result:
The main function of the program is to print the Ascii code of the character array. It can be found that the Global Array a has the same result as the dynamically generated array c, while the locally declared array B is indeed assigned a random value, maybe this is the problem.
Solution:Copy codeThe Code is as follows: # include <stdio. h>
# Include <stdlib. h>
# Define MAX 10
Char a [MAX] = {0 };
Int main ()
{
Int I;
Char B [MAX] = {0 };
Char * c = (char *) malloc (MAX * sizeof (char ));
Printf ("\ nArray a: \ n ");
For (I = 0; I <MAX; I ++)
Printf ("% d", a [I]);
Printf ("\ nArray B: \ n ");
For (I = 0; I <MAX; I ++)
Printf ("% d", B [I]);
Printf ("\ nArray c: \ n ");
For (I = 0; I <MAX; I ++)
Printf ("% d", c [I]);
Printf ("\ nDone ");
Free (c );
Return 1;
}
Running result:
In array initialization, if the number of initialized values is smaller than the size of the array, all values are filled with 0. Here, by initializing a value, you can give a definite result to the array.
(Different results may occur in different systems and compilers)
Another small problem is the space in the C language. Let's look at the following program.Copy codeThe Code is as follows: # include <stdio. h>
# Include <stdlib. h>
# Define MAX 10
Int main ()
{
Int I;
Char B [MAX] = {0 };
Gets (B );
Printf ("\ nArray B: \ n ");
For (I = 0; I <MAX; I ++)
Printf ("% d", B [I]);
Printf ("\ nDone ");
Return 1;
}
Here, I enter "int" (three spaces + int). The printed result is as follows.
The first three in B record the Ascii code of space, that is, 32.
The space not used after B is still 0.
Close the job.