学习自狄泰软件学院唐佐林老师C语言课程,文章中图片取自老师的PPT,仅用于个人笔记。
定义数组类型
通过数组类型定义数组指针,或者直接定义数组指针
实验1 : 数组类型 + 数组指针
#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];
//数组指针 通过数组类型定义数组指针并初始化 指向的目标数组是 类型为float 个数为10的 数组
AFLOAT10* pf = &fArray;
ACHAR9 cArray;//定义数组
//直接定义数组指针
char(*pc)[9] = &cArray;
// pcw是数组指针,而用来初始化数组指针的是数组首元素的地址,虽然数值和数组地址一样,但是
char(*pcw)[4] = cArray; // error
int i = 0;
printf("%d, %d\n", sizeof(AINT5), sizeof(a1));// 20 ,20
for(i=0; i<10; i++)
{
// fArray[i]
(*pf)[i] = i;
}
for(i=0; i<10; i++)
{
printf("%f\n", fArray[i]);
}
// 打印地址值
// pc+1 == (unsigned int)pc + sizeof(*pc)==pc+9
// pcw+1 == (unsigned int)pcw+ sizeof(*pcw)==pc+4
printf("%p, %p, %p\n", &cArray, pc+1, pcw+1);
return 0;
}
mhr@ubuntu:~/work/C$
mhr@ubuntu:~/work/C$
mhr@ubuntu:~/work/C$ gcc 32-1.c
32-1.c: In function ‘main’:
32-1.c:15:21: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
char(*pcw)[4] = cArray;
^
32-1.c:19:12: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]
printf("%d, %d\n", sizeof(AINT5), sizeof(a1));
^
32-1.c:19:12: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long unsigned int’ [-Wformat=]
mhr@ubuntu:~/work/C$
mhr@ubuntu:~/work/C$
mhr@ubuntu:~/work/C$
mhr@ubuntu:~/work/C$ ./a.out
20, 20
0.000000
1.000000
2.000000
3.000000
4.000000
5.000000
6.000000
7.000000
8.000000
9.000000
0x7fff72faeec0, 0x7fff72faeec9, 0x7fff72faeec4
mhr@ubuntu:~/work/C$
实验2:指针数组
#include <stdio.h>
#include <string.h>
//求数组大小
#define DIM(a) (sizeof(a)/sizeof(*a))
// 在 const char* table[] 指针数组中遍历 搜索const char* key指向的字符串 并返回下标
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;
}
mhr@ubuntu:~/work/C$
mhr@ubuntu:~/work/C$ ./a.out
4
-1
mhr@ubuntu:~/work/C$