Global and local arrays in C

  • 2020-04-01 21:29:26
  • OfStack

Today, my classmates encountered a problem of global array and local array in C language, which was stuck for a long time, and I did not see the problem at the first time. Now I will sort out the problem and give a solution.
Problem description :
Arrays declared globally have a different effect than arrays declared locally.
Let's start with a program:
 
#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 and run results:
< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201212/2012120918294113.png ">  
The main function of the program is to print the Ascii code of the character array. You can see that the global array a has the same result as the dynamically generated array c, while the locally declared array b is assigned random values, which may be the problem.
Solutions:
 
#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; 
} 

Operation results:
< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201212/2012120918294114.png ">  
In the initialization of an array, assuming that the number of initialized values is less than the size of the array, then all of them are filled with 0. By initializing a value here, you can give the array a certain result.
(different results may occur on different systems and compilers)
Another small problem is the problem of whitespace in C.
 
#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; 
} 

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201212/2012120918294115.png ">  
Here, I type "int"(three Spaces +int), and the printed result is shown in the figure above.
The first three in b record the Ascii code for Spaces, i.e. 32.
The unused space in b is still 0.
Call it a day.

Related articles: