首页 > 代码库 > C - 指针与数据

C - 指针与数据

 

一、数组

/*day_mon.c -- 打印每月的天数*/#include <stdio.h>#define MONTHS 12#define MAX_LEN 80int main(void){  /*使用const表示char为只读数据,不允许被修改*/    
  const
char months[MONTHS][MAX_LEN] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "Nobember", "December"}; int days[MONTHS] = {31, 28, 31, 30, 31, 30, 31, 31, 30 ,31, 30, 31}; int index, year; /*程序输入年份*/ puts("Enter year: "); scanf("%d", &year); /*闰年二月29天,平年28天*/ if( (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ) days[1] = 29; /*程序打印输出*/ puts("Month Day"); for(index=0; index<MONTHS; index++) printf("%s %d\n", months[index], days[index]); return 0;}

 

在整形数组中,当数组未赋值时,其值是不固定的,当没有完全赋值时,值为0.

C99新规定,可以这样初始化数组:

int arr[6] = {[5] = 212};  //把arr[5]初始化

 

二、多维数组

/*rain.c -- 针对若干年的降水量,计算年隆水总量、年降水平均量,以及月降水平均量*/#include <stdio.h>#define MONTHS 12        //一年的月份数#define YEARS 5            //降水量数据的年数int main(void){    /*把数组初始化为2010年到2014年降水量数据*/  const float rain[YEARS][MONTHS]={    {4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6},    {8.5,8.2,1.2,1.6,2.4,0.0,5.2,0.9,0.3,0.9,1.4,7.3},    {9.1,8.5,6.7,4.3,2.1,0.8,0.2,0.2,1.1,2.3,3.6,8.4},    {7.2,9.9,8.4,3.3,1.2,0.8,0.4,0.9,0.6,1.7,4.3,6.2},    {7.5,5.6,3.8,2.8,3.8,0.2,0.0,0.0,0.0,1.3,2.6,5.2}  };  int year,month;  float subtot, total;  printf(" YEAR RAINFALL (inches) \n");  for(year = 0, total = 0; year < YEARS; year++)  {    for(month = 0,subtot = 0; month < MONTHS; month++)    {      subtot += rain[year][month];     }    printf("%5d %15.1f\n", 2010+year, subtot);    total += subtot;  }  printf("\nThe yearly average is %.1f inches. \n\n ", total/YEARS);  printf("MONTHLY AVERAGES: \n\n");  printf("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\n");    for(month = 0; month < MONTHS; month++)  {    for(year=0,subtot=0; year<YEARS;year++)    subtot += rain[year][month];    printf("%4.1f", subtot/YEARS);  }   printf("\n");  return 0; }

 

一维数组是排成一行的数据

二维数组是放在平面上的数据

三维数组是把平面数据一层一层垒起来

 

三、指针和数组

指针提供了一种使用内存地址的符号的方法。

int a[100];a == &a[0]  //数组名同时也是该数组首元素的地址。

 

C - 指针与数据