执行结果 :
[root@ip28 struct]# gcc word_count.c [root@ip28 struct]# ./a.out auto break break char 1 auto 2 break 1 char
宏定义方法 : 获取结构体数组大小;
-- sizeof 方法 : sizeof (对象) | sizeof (类型名称) 可以获取对象 或者 类型占用的存储空间, 其返回值是 size_t 类型的, 定义在stddef.h 头文件中;
-- 使用类型测量 :
#define KEYS (sizeof(key_count) / sizeof(struct key))-- 使用对象测量 :
#define KEYS (sizeof(key_count) / sizeof(struct key_count[0])
4. 指向结构体指针
(1) 使用指针方式实现上面的关键字统计程序
使用指针进行二分查找 :
-- 使用下标找中值 : 在之前找中值时通过 mid = (low + high)方法, 这样做可行是因为 low 从0开始的;
-- 如果是指针情况 : mid low high 都是指针, 那么就不能使用上面的那种方法了, 使用 mid = low + (high - low) / 2;.
-- 指针操作情况的 high 和 low : 其中 low 是首元素的 首地址, high 是 尾元素的尾地址, 只有这样 它们的差的 0.5 倍才是准确的中值的首地址;
指针指向数组注意点 : 不要生成非法的指针, 指针不能指向数组之外的元素;
-- &key_count[-1] : 这个指针时非法的;
-- &key_count[n] : 对数组的最后一个元素后面的第一个元素进行 & 运算时合法的, 其它操作都是非法的;
示例程序 :
/*************************************************************************
> File Name: pointer_struct.c
> Author: octopus
> Mail: octopus_work.163.com
> Created Time: Tue 25 Mar 2014 12:31:08 AM CST
************************************************************************/
#include
#include
#include
#define MAXWORD 20 /*计算结构体数组的大小*/ #define KEYS (int)(sizeof(key_count) / sizeof(struct key)) struct key { char *word; int count; } key_count[] = { auto, 0, break, 0, case, 0, char, 0, const, 0 }; int getword(char *, int); struct key *binsearch(char*, struct key*, int); int main(int argc, char **argv) { char word[MAXWORD]; struct key *p; /*存放查找方法返回的结构体指针, 该指针指向数组中查找到元素的下标*/ while(getword(word, MAXWORD) != EOF) if(isalpha(word[0])) if((p = binsearch(word, key_count, KEYS)) != NULL) p->count++; for(p = key_count; p < key_count + KEYS; p++) if(p->count > 0) printf(%2d %s , p->count, p->word); return 0; } /* * 没有循环控制变量的 for 循环, 在内部通过条件 break */ int getword(char *word, int max) { int c, getc(