《C语言入门经典》第5版 Ivor Horton 第五章 数组 读书笔记
5.1.2 什么是数组
数组是 一组 数目固定、类型相同 的数据项,数组中的数据项 称为 元素,数组中的元素 都是 int、long 或其他类型。
访问数组元素的值,有两种方法指定 索引值:
① 使用一个简单的整数,明确指定要访问的元素;
② 使用一个在执行期间计算的整数表达式(限制:结果必须是整数,该整数必须是对数组有效的索引值)。
5.2 寻址运算符 (&)
输出其操作数的内存地址,把寻址运算符放在变量名称之前,函数就可以利用这个变量的地址,修改在这个变量中存储的值。
输出一些变量的地址:
#include <stdio.h>
int main(){
// 定义一些整型变量
long a = 1L;
long b = 2L;
long c = 3L;
// 定义一些浮点型变量
double d = 4.0;
double e = 5.0;
double f = 6.0;
printf("A variable of type long occupies %u bytes.\n", sizeof(long));
printf("Here are the address of some variables of type long:\n");
printf("The address of a is: %p\nThe address of b is: %p\nThe address of b is: %p\n", &a, &b, &c);
printf("A variable of type double occupies %u bytes.\n", sizeof(double));
printf("Here are the address of some variables of type long:\n");
printf("The address of d is: %p\nThe address of e is: %p\nThe address of f is: %p\n", &d, &e, &f);
return 0;
}
运行结果:
显示出来的地址,地址值逐渐变小,呈等差数列,地址 b 比 a 低 4,地址 e 比 d 低 8。
变量 d 和 c 的地址 之间有一个空隙的原因:
许多编译器给变量分配内存地址时,其地址都是 变量字节数 的倍数,所以 4 字节变量的地址是 4 的倍数,8 字节变量的地址 是 8 的倍数。这就确保内存的访问是最高效的。(如果间隔大于 变量字节数,可能是调试版本模式下,会配置额外的空间)
5.3 数组和地址
索引值 表示 各个元素 与 数组开头 的偏移量
5.5 确定数组的大小
double values[5] = {1.5, 2.5, 3.5, 4.5, 5.5};
size_t element_count = sizeof(values)/sizeof(values[0]);
printf("The size of the array is %d bytes ", sizeof(values));
printf("and there are %d elements of %d bytes each\n", element_count, sizeof(values[0]));
表达式 sizeof values[0] 可以输出数组中一个元素所占的字节数。size_t 类型是 sizeof 运算符生成的类型。
循环处理数组中的所有元素时,可以使用 sizeof 运算符:
double values[5] = {1.5, 2.5, 3.5, 4.5, 5.5};
double sum = 0.0;
for(int i = 0; i < sizeof(values)/sizeof(values[0]); i++)
sum = values[i];
printf("The sum of the values is %.2f", sum);
5.6 多维数组
5.7 多维数组的初始化
要处理多维元素数组中的所有元素,需要一个嵌套循环。嵌套的层数 就是 数组的维数。