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:
#include <stdio.h>#include <stdlib.h>#define MAX 10char 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:
#include <stdio.h>#include <stdlib.h>#define MAX 10char 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.
#include <stdio.h>#include <stdlib.h>#define MAX 10int 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.