c语言数组的使用对于初学者来说常常是个问题.数组的声明不难,尤其是一维数组;万恶之源可能在于数组下标从[0]开始.
声明一个int型的数组,像这样:
int something[5];
于是数组元素从something[0]到something[4]是合法的.
然而,由于c语言对数组越界审查不严格,对于不同的计算机和操作系统,若数组越界是可以通过编译的,甚至是可以运行的;
但作为一名合格的c程序员,我们不仅得从0开始数数,还要避免数组越界(除非特殊情况)
下面这段代码读入字母,排序,输出:
#include <stdio>
#include <stdlib.h>
#define ARSIZE 10
int main(){
int ch_arr[ARSIZE],count1;
int count2, stop, lastchar;
lastchar = 0;
stop = 0;
/*
* Read characters into array.
* Stop if end of line, or array full.
*/
while(stop != 1){
ch_arr[lastchar] = getchar();
if(ch_arr[lastchar] == '\n')
stop = 1;
else
lastchar = lastchar + 1;
if(lastchar == ARSIZE)
stop = 1;
}
lastchar = lastchar-1;
/*
* Now the traditional bubble sort.
*/
count1 = 0;
while(count1 < lastchar){
count2 = count1 + 1;
while(count2 <= lastchar){
if(ch_arr[count1] > ch_arr[count2]){
/* swap */
int temp;
temp = ch_arr[count1];
ch_arr[count1] = ch_arr[count2];
ch_arr[count2] = temp;
}
count2 = count2 + 1;
}
count1 = count1 + 1;
}
count1 = 0;
while(count1 <= lastchar){
printf("%c\n", ch_arr[count1]);
count1 = count1 + 1;
}
return 0;
}
这里定义了一个常量ARSIZE,做到一改全改