Let's know more about '数组'
来源:互联网 发布:大数据体系 编辑:程序博客网 时间:2024/06/09 20:50
引子
上回我们对数组的了解只停留在一维层次上的认识,可实际上在C语言中是存在多维数组的。在这一节中我们不仅要了解多维数组,还要对数组的空间地址做一个的小小的了解。
在这里先对数组入门这一章做一个补充
在数组的使用中我们要避免数组越界的情况出现,要知道编译器对于数组索引是不会报错的哦!!!下面我们通过例子来说明这一点
/* Note:Your choice is C IDE */#include "stdio.h"void main(){ int a=0; int b[3]={2,4,3}; int c=0; printf("a=%2d b[0]=%2d b[1]=%2d b[2]=%2d c=%2d\n",a,b[0],b[1],b[2],c); b[-1]=-1; //越界情况 b[3]=-3; //越界情况 printf("\n执行b[-1]= -1 b[3]=-3\n\n"); printf("a=%2d b[0]=%2d b[1]=%2d b[2]=%2d c=%2d",a,b[0],b[1],b[2],c); }
运行结果如下
a= 0 b[0]= 2 b[1]= 4 b[2]= 3 c= 0
执行b[-1]= -1 b[3]=-3
a=-3 b[0]= 2 b[1]= 4 b[2]= 3 c=-1
这个例子告诉我们数组的越界使用是十分危险的,至于为什么会出现这样的情况是与程序的内存分配有关,在这里不需要深入研究。
1、多维数组
定义多维数组及空间储存方式
/* Note:Your choice is C IDE */#include "stdio.h"void main (){ int i, t; int a[3][4] = { {1,2,3,8}, {0,9}, {4,5,8,6}, //注意文风,增加代码可读性 }; for(i = 0; i < 3; i++) { printf ("\n"); for(t = 0; t < 4; t++) printf ("%d ", a[i][t]); }}
结果如下
1 2 3 8
0 9 0 0
4 5 8 6
小程序 杨辉三角形(自己动手编写,着重强调二维数组的运用)
#include "stdio.h"void main(){ int a[8][8],i,j; for(i=0;i<8;i++) for(j=0;j<=i;j++) { if(j==0) a[i][j]=1; else if(i==j) a[i][j]=1; else a[i][j]=a[i-1][j-1]+a[i-1][j]; } for(i=0;i<8;i++) { for(j=0;j<=i;j++) printf("%-3d",a[i][j]); printf("\n"); }}
2、关于地址的几个符号
在多维数组中我们以二维数组为例,储存方式可按行、列储存,在此不再赘述。关于数组还要强调的地址的一些小玩意需要注意,仔细观察下列程序
#include "stdio.h"void main(){ int i,a[4]={4,5,8,6}; for(i=0;i<4;i++) printf("a[%d] = %d ", i, a[i]); //输出a[i]的元素 printf ("\na[0] = %d", a[0]); //输出a[0]的值 printf ("\na = %d", a); //输出a[0]的空间地址 printf ("\n&a[0] = %d", &a[0]); //输出a[0]的空间地址 printf ("\n*a = %d", *a); //通过地址读取内容值 printf ("\na+1 = %d", a+1); //输出a[1]的空间地址 printf ("\n*(a+1) = %d", *(a+1)); //通过地址读取内容值a[1]}
运行结果如下
a[0] = 4 a[1] = 5 a[2] = 8 a[3] = 6
a[0] = 4
a = 1703724
&a[0] = 1703724
*a = 4
a+1 = 1703728
*(a+1) = 5
通过这个小程序,我们可以了解到
1、a 代表a这个数组的首位元素地址空间
2、& 在C语言中是取地址符,由于a表示数组的首位元素地址空间,即有:
a = &a[0] //a[0]的空间地址
a+1=&a[1] //a[1]的空间地址
3、* 表示取内容
a[0]=*a
a[1]=(a+1) //注意与+的优先级
最后一点点关于*、&的使用是为了指针的学习埋伏笔,要求理解*、&的作用即可。
本章完。。。
- Let's know more about '数组'
- Let you know more about NFL team-New jersey Devils
- know more about sementic
- Know more about checkpoint
- Know more about Oracle Nologging
- Know more about checkpoint
- Know more about your customer…
- Getting To Know More About The Best Clothing Embroidery
- More than you ever wanted to know about GeoJSON
- Know more about RAC statistics and wait event
- Know More About LC And SC Fiber Patch Cable
- OK, let's talk about ASUS
- Let's talk about search engine...
- Let's Talk About project.pbxproj
- 10 Things You Should Know About Microsoft's Silverlight
- Franklin let me know
- Know about wine
- Use Your Wisdom to Know When It's Time to Let Go
- Linux swap命令
- ACboy needs your help HDU
- Qt UDP组播的应用
- 《零基础入门学习Python》学习笔记2
- Java的包
- Let's know more about '数组'
- 多视角半监督学习:从文本数据中得到不同视角
- MySQL初学者简要操作说明
- 输入三个数,得到最大值
- 在linux+nginx+mysql+php环境下安装 phpmyadmin
- Eclipse Java汉化
- 交叉编译环境搭建
- 06 ???
- 几种画辅助线的方式