C语言中全局数组和局部数组的问题
语言中全局数组和局部数组的问题
今天同学遇到一个在语言中全局数组和局部数组的问题,卡了许久,我也没有第一时间看出问题,现在把问题梳理一下,并给出解决方案。
问题描述:
在全局声明的数组与在局部声明的数组有着不同的效果。
首先来看一个程序:
代码如下:
#
#
# X 10
[X];
()
{
;
[X];
*=( *)(X * ());
(“ : “);
(=0; (“% “,[]);
(“ : “);
(=0; (“% “,[]);
(“ : “);
(=0; (“% “,[]);
(“ ”);
();
1;
}
编译运行结果:
程序主要功能是打印字符数组的码语言中全局数组和局部数组的问题。可以发现全局数组和动态生成的数组有着相同的结果,而局部声明的数组确被分配了随机的数值,也许这就是问题的所在。
解决方案:
代码如下:
#
#
# X 10
[X]={0};
()
{
;
[X]={0};
*=( *)(X * ());
(“ : “);
(=0; (“% “,[]);
(“ : “);
(=0; (“% “,[]);
(“ : “);
(=0; (“% “,[]);
(“ ”);
();
1;
}
运行结果:
在数组的初始化中,假设初始化的数值个数小于数组的大小,则全部用0来填充语言中全局数组和局部数组的问题。这里通过初始化一个值,就可以给数组一个确定的结果。
(在不同系统和不同的编译器可能会出现不同的结果)
还有一个小问题就是语言中空格的问题,看下面的程序。
代码如下:
#
#
# X 10
()
{
;
[X]={0};
();
(“ : “);
(=0; (“% “,[]);
(“ ”);
1;
}
在这里,我输入了” ”(三个空格+),打印的结果如上图语言中全局数组和局部数组的问题。
中前三个记录了空格的码,即32。
中后面没有使用的空间依然是0.
daily morning exercises or class-break setting-up exercise and discipline inspection and appraisal of public signs;2, daily cleaning and inspection;3, the daily student school appearance, dress, wearing school card check;4, the daily duty guide to the leadership class discipline three rounds.Weekly moral education work:L, the flag raising ceremony and the "national flag" speech under the flag raising ceremony held on Monday";2, every week a class meeting, the meeting;3, every week "two exercises, cleaning and hygiene, behavior norms, attendance" situation published cloth appraisal, and the issue of the code of conduct;;4, weekly work week.Monthly moral education work:1, at least once a month, the theme of education activities, to patriotism education, behavior norms of education as the focus, combined with major retreat day.2, the monthly c