數組是相同類型的變量的有序集合。
int a[5]; // 5個int類型數據,每個元素都是int型數據;a代表數組第一個元素的起始地址。這20個字節空間的名字
爲a,a[0]、a[1]等都是a中的元素,並非元素的名字。數組中的元素沒有名字。
數組的大小:數組在一片連續的內存空間中存儲元素
數組元素的個數可以顯式或隱式指定
int main()
{
int a[5] = {1, 2};
int b[] = {3, 4};
printf("%d, %d, %d\n", a[2], a[3], a[4]);
int a1 = sizeof(a);
int b1 = sizeof(b);
printf("%d, %d\n", a1, b1);
int an = a1/sizeof(int);
int bn = b1/sizeof(int);
printf("%d, %d\n", an, bn);
return 0;
}
編譯運行:
~/will$ ./a.out
0, 0, 0
20, 8
5, 2
數組名代表數組首元素的地址;數組的地址需要用取地址符&才能得到;
數組首地址的地址值與數組的地址值相同;
數組首元素的地址與數組的地址是兩個不同的概念。//首地址是一個地址,而數組的地址是一個包含數組長度的地址
int main()
{
int a[5] = {1, 2, 3, 4, 5};
printf("%p\n", a);
printf("%p\n", &a);
printf("%p\n", &a[0]);
return 0;
}
但是編譯運行的結果是一樣的:
~/will$ ./a.out
0xbfae18fc
0xbfae18fc
0xbfae18fc
數組名可以看做一個常量指針數組名“指向”的是內存中數組首元素的起始位置
數組名不包含數組的長度信息
在表達式中數組名只能作爲右值使用
只有在下列場合中數組名不能看做常量指針數組名作爲sizeof操作符的參數
數組名作爲&運算符的參數
觀察下面代碼:
int main()
{
int a[5] = {1, 2, 3, 4, 5};
int b[2];
int* p = NULL;
p=a;
printf("%p\n", a);
printf("%p\n", p);
printf("%p\n", &a);
printf("%p\n", &p);
printf("sizeof(a) = %d\n",sizeof(a));
printf("sizeof(p) = %d\n",sizeof(p));
printf("\n");
p=b;
printf("%p\n", b);
printf("%p\n", p);
printf("%p\n", &b);
printf("%p\n", &p);
printf("sizeof(b) = %d\n",sizeof(b));
printf("sizeof(p) = %d\n",sizeof(p));
//b = a; error
return 0;
}
編譯運行:
~/will$ gcc test.c
~/will$ ./a.out
0xbfeb7260
0xbfeb7260
0xbfeb7260
0xbfeb727c
sizeof(a) = 20
sizeof(p) = 4
0xbfeb7274
0xbfeb7274
0xbfeb7274
0xbfeb727c
sizeof(b) = 8
sizeof(p) = 4
數組是一片連續的內存空間
數組的地址和數組首元素的地址意義不同
數組名在大多數情況下被當做常量指針處理
數組名其實不是指針,不能將其等同於指針,比如兩個大小不同的數組,是不能用數組名相互賦值的。