-
定义数组类型
typedef type(name)[size];
例如:
数组类型: typedef int(AINT5)[5]; typedef float(AFLOAT10)[10];
数组定义: AINT5 iArray; AFLOAT10 fArray;
int array[5]; int matrix[3][3];
int *pA=array; int *pM=matrix;
array代表数组首元素的地址,&array数组的地址
matrix:代表二维数组首个数组的地址。&matrix:代表整个二维数组的地址
2.数组指针
通过类比可以得到:
普通类型: int *pi; int i; pi=&i;
数组类型:arrayType *p; int array[5] ; p=&array;
实例分析:
数组类型的定义 数组指针的使用 数组指针的运算
#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;
}
for (i = 0; i<10; i++)
{
printf("%f\n", fArray[i]);
}
printf("%0X, %0X, %0X\n", &cArray, pc + 1, pcw + 1);
}
指针数组
例子:指针数组的使用(关键字查找)
#include <stdio.h>
#include <string.h>
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;
}
#define DIM(a) (sizeof(a)/sizeof(*a))
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;
}
main函数的参数
#include <stdio.h>
int main(int argc, char* argv[], char* env[])
{
int i = 0;
printf("============== Begin argv ==============\n");
for (i = 0; i<argc; i++)
{
printf("%s\n", argv[i]);
}
printf("============== End argv ==============\n");
printf("\n");
printf("\n");
printf("\n");
printf("============== Begin env ==============\n");
for (i = 0; env[i] != NULL; i++)
{
printf("%s\n", env[i]);
}
printf("============== End env ==============\n");
return 0;
}