简单数组

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,做到一改全改
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值