-
数组类型
-C语言中的数组有自己特定的类型 -数组的类型由元素类型和数组大小共同决定 --int array[5]的类型为int[5]
-
定义数组类型
-C语言通过typedef为数组类型重命名 --typedef type(name)[size] -数组类型: --typedef int(AINT)[5]; typedef float(AFLOAT10)[10]; -数组定义: --AINT5 iArray; AFLOAT10 fArray;
-
数组指针
-数组指针用于指向一个数组 -数组名是数组首元素的起始地址,但并不是数组的起始地址 -通过将取地址符&作用域数组名可以得到数组的起始地址 -可通过数组类型定义数组指针: ArrayType* pointer; -也可以直接定义: type(* pointer)[n]; pointer为数组指针变量名 type为指向数组的元素类型 n为指向数组的大小
代码示例:
#include <stdio.h>
typedef int(AINT5)[5];
typedef float(AFLOAT10)[10];
typedef char(ACHAR9)[9];
int main()
{
AINT5 a1;
float fArray[10];
AFLOAT10* pf = &fArray;
ACHAR9 cArray;
char(*pc)[9]= &cArray;
char(*pcw)[4] = cArray; //此处会有个警告指针类型不同赋值出错
int i = 0;
printf("%d, %d\n", sizeof(AINT5), sizeof(a1));
for(i=0; i<10; i++)
{
(*pf)[i] = i; // ==> fArray[i] = i;
}
for(i=0; i<10; i++)
{
printf("%f\n", fArray[i]);
}
printf("%p, %p, %p\n", &cArray, pc+1, pcw+1); //pc + 1 ==> (unsigned int)pc + 9
return 0;
}
编译结果:
-
指针数组
-指针数组是一个普通的数组 -指针数组中每个元素为一个指针 -指针数组的定义: type* pArray[n]; type*为数组中每个元素的类型 pArray为数组名 n为数组大小
代码示例:
#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;
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[] = {
"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;
}
编译结果