注:博客中内容主要来自《狄泰软件学院》,博客仅当私人笔记使用。
测试环境:Ubuntu 10.10
GCC版本:4.4.5
一、思考
1) 下面这些声明合法吗?
int array[5];
int matrix[3][3];
int* pa = array;
int* pm = matrix;不合法
问题:
array代表数组首元素的地址,那么matrix代表什么?matrix[3][0]
array和&array的地址值相同,但是意义不同,那么它们所代表的类型相同吗?
array==&a[0] &array==int (*)[5]
二、数组类型
1) C语言中的数组有自己特定的类型
2) 数组的类型由元素类型和数组大小共同决定
例:int array[5]的类型为int[5]
工作中的对话...
A:这里定义的数组什么类型的?
B:int型... 错误说法
数组没有int型,还需要包含大小。
三、定义数组类型
1) C语言中通过typedef为数组类型重命名
typedef type(name)[size]
- 数组类型:
typedef int(AINT5)[5];
typedef float(AFLOAT10)[10];
- 数组定义:
AINT5 iArray;
AFLOAT10 fArray;
四、数组指针
1) 数组指针用于指向一个数组
2) 数组名是数组首元素的起始地址,但并不是数组的起始地址(从数组类型角度理解)
3) 通过将取地址符&作用于数组名可以得到数组的起始地址
4) 可通过数组类型定义数组指针:ArrayType* pointer;
5) 也可以直接定义:type(*pointer)[n];
pointer为数组指针变量名
type为指向的数组的元素类型
n为指向的数组的大小
实例分析
数组类型和数组指针
32-1.c
#include <stdio.h>
typedef int (AINT5)[5];
typedef float (AFLOAT10)[10];
typedef char (ACHAR9)[9];
int main()
{
AINT5 a1; //int a1[5]
float fArray[10]; //浮点型数组
AFLOAT10* pf = &fArray; //AFLOAT10* ==> float (*)[10]
ACHAR9 cArray; //char cArray[9]
char(*pc)[9] = &cArray; //数组指针
char(*pcw)[4] = cArray; //类型不同,会有警告
int i = 0;
printf("%d, %d\n", sizeof(AINT5), sizeof(a1));//20,20
for(i=0; i<10; i++)
{
(*pf)[i] = i; //解引用数组指针赋值,即fArray[i] = i
}
for(i=0; i<10; i++)
{
printf("%f\n", fArray[i]); //打印0到9
}
printf("%p, %p, %p\n", &cArray, pc+1, pcw+1);
/*
&cArray => 数组首地址
pc+1 => (unsigned int)pc + 9(sizeof(char [9]))
pcw+1 => (unsigned int)pc + 1(sizeof(char ()[4]))
*/
return 0;
}
操作:
1)gcc 32-1.c -o 32-1.out编译有警告:
32-1.c:15:19: warning: initialization from incompatible pointer type [enabled by default]
char (*pcw)[4] = cArray;
^
警告:初始化指针类型时不兼容
用数组类型初始化数组指针
打印结果:
20, 20
0.000000
1.000000
2.000000
3.000000
4.000000
5.000000
6.000000
7.000000
8.000000
9.000000
0xbfe378f3, 0xbfe378fc, 0xbfe378f7
五、指针数组
1) 指针数组是一个普通的数组
2) 指针数组中每个元素为一个指针
3) 指针数组的定义:type* pArray[n];
type*为数组中每个元素的类型
pArray为数组名
n为数组大小
实例分析
指针数组的应用
32-2.c
#include <stdio.h>
#include <string.h>
#define DIM(a) (sizeof(a)/sizeof(*a)) //得到数组大小,预编译阶段完成
//查找关键字
int lookup_keyword(const char* key, const char* table[], const int size)
{
int ret = -1; //-1表示错误
int i = 0;
for(i=0; i<size; i++)
{
if( strcmp(key, table[i]) == 0 ) //字符串比较
{
ret = i;
break;
}
}
return ret;
}
int main()
{
const char* keyword[] = { //常量指针数组,char* keyword[]不能修改
"do",
"for",
"if",
"register",
"return",
"switch",
"while",
"case",
"static"
};
printf("%d\n", lookup_keyword("return", keyword, DIM(keyword)));
printf("%d\n", lookup_keyword("main", keyword, DIM(keyword)));
return 0;
}
操作:
1) gcc 32-2.c -o 32-2.out编译正确,打印结果:
4
-1
分析:
指针数组存储字符串很方便,每个元素存储的是字符串的地址。
小结:
1) 数组的类型由元素类型和数组大小共同决定
2) 数组指针是一个指针,指向对应类型的数组
3) 指针数组是一个数组,其中每个元素都为指针
4) 数组指针遵循指针运算法则
5) 指针数组拥有C语言数组的各种特性