C 程序设计语言——第六章笔记

C 程序设计语言第二版——第六章笔记


参考:

c 程序设计语言第二版英文版(K&R)6.4 p136

6.4 指向结构体的指针

修改 keyword-counting 程序,使用指针代替数组索引,程序如下:

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAXWORD 100
int getword(char *, int);
struct key *binsearch(char *, struct key *, int);
/* count C keywords; pointer version */
main()
{
char word[MAXWORD];
struct key *p;
while (getword(word, MAXWORD) != EOF)
if (isalpha(word[0]))
if ((p=binsearch(word, keytab, NKEYS)) != NULL)
p->count++;
for (p = keytab; p < keytab + NKEYS; p++)
if (p->count > 0)
printf("%4d %s\n", p->count, p->word);
return 0;
}
/* binsearch: find word in tab[0]...tab[n-1] */
struct key *binsearch(char *word, struck key *tab, int n)
{
int cond;
struct key *low = &tab[0];
struct key *high = &tab[n];
struct key *mid;
while (low < high) {
mid = low + (high-low) / 2;
if ((cond = strcmp(word, mid->word)) < 0)
high = mid;
else if (cond > 0)
low = mid + 1;
else
return mid;
}
return NULL;
}

分析:

  1. 在 binsearch 程序中,选取指向中间元素的指针的方法为:
mid = low + (high - low) / 2;

而不是像数组索引里的:

mid = (low + high) / 2;

因为指针不能相加,只能相减,指针操作见C Primer Plus— Chapter 10—Arrays and Pointers —2. 指针和数组
指针相减得到两个指针之间相隔的元素数量,为整型值,再加上指针 low,即可得到指向中间元素的指针。
2. 结构体的大小
结构体的大小并不一定是所有成员大小的和,因为存在对齐的要求。
见:
Why isn’t sizeof for a struct equal to the sum of sizeof of each member?
C-FAQ
The Lost Art of Structure Packing
测试程序:
```
#include<stdio.h>
int main(void)
{
struct key {
char c;
int i;
} a = { ‘a’, 3};
printf(“sizeof(a) : %zd\n”, sizeof(a));
return 0;
}

输出:

sizeof(a) : 8

因为 int i 需要4字节,因此 char c 与它对齐,要补上3字节,实际如下:

struct key {
char c; /* 1 bytes /
char pad[3]; /
3 byte /
short i; /
4 byte*/
};



发布了120 篇原创文章 · 获赞 2 · 访问量 5815

猜你喜欢

转载自blog.csdn.net/Lee567/article/details/102985357