C:数组

来源:互联网 发布:mysql 配置优化 编辑:程序博客网 时间:2024/06/11 12:09

1. 什么是数组

数组是一组数目固定,类型相同的数据项,数组中的数据项称为元素。
数组中的元素固定,每个数组的元素都是 int,long或其他类型。
声明一个数组:
long numbers[10];
括号中的数字定义了要存放数组中的元素个数,称为数组维 array dimension;

数组中的每个值由索引值(index value)来识别,
索引值是一个整数。从0开始的连续整数。

如果程序里使用的索引值超过了数组的合法范围,程序将不能正常运行。
编译器检查不出这种错误,程序仍可以编译,但是执行是有问题的。

2. 内存

计算机的内存可以看做一排很整齐的盒子,每个盒子有2中状态:满(称为 1 )和空(称为 0),
每个盒子都包含一个二进制数,称为 位( bit )
为了方便, 8个盒子组合为一组,每组称为字节(byte)
要辨识每个字节,以访问其内容,用数字标记字节,称为地址。

& 称为寻址运算符,
广泛用于scanf函数, &放在变量名前面,获取变量的地址。
#include <stdio.h>int main(void){    long a = 1L;     long b = 2L;     long c = 3L;     double d = 4.0;    double e = 5.0;    double f = 6.0;    printf("long type occupies %lu bytes\n", sizeof(long));    printf("address of a is: %p, b is : %p, c is : %p\n\n", &a, &b, &c);    printf("double type occupies %lu bytes\n", sizeof(double));    printf("address of d is : %p, e is : %p, f is : %p\n", &d, &e, &f);    return 0;}
执行结果
$ ./a.out long type occupies 8 bytesaddress of a is: 0x7fff5dff2c00, b is : 0x7fff5dff2bf8, c is : 0x7fff5dff2bf0double type occupies 8 bytesaddress of d is : 0x7fff5dff2be8, e is : 0x7fff5dff2be0, f is : 0x7fff5dff2bd8
格式指定符%p, 来输出变量的内存地址,16进制。
long类型占8个字节, 输出的地址逐渐变小,b比a低8, c比b低8.

3. 数组与地址

声明数组时,指定值的类型和元素个数。值的类型决定了每个元素需要的字节数。
看数组的地址,和存储的内容:
#include <stdio.h>int main(void){    int data[5];    for(int i = 0; i<5; i++){        data[i] = 12 * (i + 1);         printf("data[%d] address: %p, content: %d\n", i, &data[i], data[i]);    }       return 0;}
执行结果
$ ./a.out data[0] address: 0x7fff5bd97bf0, content: 12data[1] address: 0x7fff5bd97bf4, content: 24data[2] address: 0x7fff5bd97bf8, content: 36data[3] address: 0x7fff5bd97bfc, content: 48data[4] address: 0x7fff5bd97c00, content: 60
每个元素地址大于前一个元素, 占用4个字节。

4. 数组的初始化

double values[3] = {1.5, 2.5, 3.5};
声明包含3个元素的数组values。
double values[5] = {1.5, 2.5, 3.5};
如果初始的个数(3个)少于元素数(5),则后面元素初始为0;
如果初始的个数大于元素数,编译器就会报错。
int primes[] = {1, 2, 3, 4, 5};
没有指定元素个数, 则根据初始值个数确定, 上面的primes数组有5个元素。

5. 数组的大小

sizeof可以计算指定类型变量占用的字节数。
#include <stdio.h>int main(void){    printf("long type size is : %lu bytes.", sizeof(long));    double value = 1.0;    printf("\n the size of value is %lu bytes.", sizeof value);    return 0;}
执行结果
$ ./a.out long type size is : 8 bytes. the size of value is 8 bytes.
sizeof 可以用于数组。
    double values[5] = {1.5, 2.5, 3.5, 4.5, 5.5};    printf("the size of values array, is : %lu bytes.\n", sizeof values);//结果the size of values array, is : 40 bytes.
5个元素,每个元素double占8个字节, 共40字节。

6. 多维数组

float number[3][5];
一个3行5列的数组。
#include <stdio.h>int main(void){    int numbers[3][4] = {         {10, 20, 30, 40},        {50, 60},    };      printf("this size of numbers is %lu\n", sizeof numbers);    return 0;}//结果this size of numbers is 48
3行4列, 没有赋值的元素默认为0. 总共占48字节, int为4bytes。

地址:http://blog.csdn.net/yonggang7/article/details/51416314

0 0
原创粉丝点击