一、数组
所谓数组,就是相同数据类型的元素按一定顺序排列的集合。
在C/C++里,int str[5] = {1,2,3,4,5}就是一个有五个元素的数组
注意:
str[0] = 1;//数组的下标从0开始,到 n-1
二、数组如何打印
(1)基础版
方法:
利用for循环,增加变量i根据数组长度来判断循环的次数
代码块:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int str[5] = {1,2,3,4,5};
for(int i = 0; i<5 ;i++)
{
printf("%d ",str[i]);
}
printf("\n");
system("pause");
return 0;
}
运行结果:
解析:
这个方法想必学过C语言的人都会写
那么这个方法有没有问题呢?
嗯,的确,她只可以针对单独的数组,假设换一个数组,并不一定会可以通用
(2)强化版—》利用sizeof实现通用性
方法:
利用 sizeof(str) / sizeof(str[0])来求出数组长度
由于在前面已经讨论过sizeof,这里就不多说了。详细请看链接 http://blog.csdn.net/qq_31828515/article/details/51646693
代码块:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int str[5] = {1,2,3,4,5};
int i = 0;
for (i = 0; i<sizeof(str) / sizeof(str[0]); i++)
{
printf("%d ", str[i]);
}
system("pause");
return 0;
}
运行结果:
解析:
然后 除以 sizeof(str[0])第一个元素的长度
就可以求出数组元素的个数了
不信试试
(3)拔高版—》学会封装的思想
方法:
①什么是封装?
就是将一个功能块(比如打印数组),封装成一个函数
以后我们用这个函数,可以实现所有数组的打印。避免代码重用,减少代码量
②封装代码块(有问题吗??)
#include<stdio.h>
#include<stdlib.h>
void Print(int str[])
{
int i = 0;
for (i = 0; i<sizeof(str) / sizeof(str[0]); i++)
{
printf("%d ", str[i]);
}
printf("\n");
}
int main()
{
int str[5] = { 1, 2, 3, 4, 5 };
Print(str);
system("pause");
return 0;
}
的确,是有问题的
③出现问题?
为什么不能正常输出?
因为数组传递的时候,仅仅只是传递地址。 (你总不能把数组所有元素全部拷贝一份吧!太占用空间了)
真正代码块:
#include<stdio.h>
#include<stdlib.h>
void Print(int str[],int n)
{
int i = 0;
for (i = 0; i<n; i++)
{
printf("%d ", str[i]);
}
printf("\n");
}
int main()
{
int str[5] = { 1, 2, 3, 4, 5 };
int n = sizeof(str)/sizeof(str[0]);
Print(str,n);
system("pause");
return 0;
}
运行结果:
小结:
数组作为形参传递的时候,只是将首地址穿过来
要注意到这个问题,以后就可以避免这样的错误再次发生了
——》》》sizeof关键字