Today, students encounter a global array in C language and local array problem, card for a long time, I do not see the first problem, now to comb the problem, and give a solution.
Problem Description:
An array that is declared globally has a different effect than a locally declared array.
First look at a program:
Copy Code code 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 Run Results:
The main function of the program is to print the ASCII code of the character array. You can see that global array A and dynamically generated array C have the same result, while the locally declared array B is indeed assigned a random number, perhaps that's where the problem lies.
Solution:
Copy Code code 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;
}
Run Result:
In the initialization of an array, assuming that the number of values initialized is less than the size of the array, all are populated with 0来. Here, by initializing a value, you can give the array a definite result.
(different results may occur in different systems and different compilers)
There is also a small problem is the C language of the problem, look at the following procedures.
Copy Code code 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 entered "int" (three spaces +int) and printed the results as shown above.
The first three in B is a space-logged ASCII code, that is, 32.
The unused space in the back of B is still 0.
Finish the call.