用间接寻址方法实现表

w346581442 2012-06-26 08:28:07
typedef ListItem *addr;
typedef struct indlist *List;
typedef struct indlist{
int n;
int maxsize;
addr *table;//?
}Indlist;

List ListInit(int size)
{
List L=malloc(sizeof*L);
L->n=0;
L->maxsize=size;
L->table=malloc(size*sizeof(addr));//?
return L;
}

ListItem ListRetrieve(int k,List L)
{
if(k<1||k>L->n)Error("out of bounds");
return *L->table[k-1];//?

有问号的都是不懂的请指教啊
}
...全文
168 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
gongzilv 2012-06-27
  • 打赏
  • 举报
回复
搂住还不适应typedef吧,你把typedef定义前的类型替换进去理解就比较清楚了。
例如 addr *table; 实际上就是 ListItem **table;
typedef可以把一个复杂的类型重命名成简单明确或自己喜欢的名字
firendlys 2012-06-26
  • 打赏
  • 举报
回复
这个破csdn ...打了我n久的字居然就这么消失了.....汗....

那就再简单说一下吧, 其实就是指针的指针.

第一个问号处,简单将addr替换一下,table的类型就变成 ListItem** ,即指向一个 ListItem* 的数组(这个数组的空间在你第二个问号处分配).

之后你第3个问号,其实就是获取一个ListItem的值, 因为 table指向一个数组, 自然, table[k-1] 就是这个table指向的数组的第k-1个元素的值了.而这个值实际上是一个 ListItem* 的指针.
之后,在return之前, 用 * 运算符将 ListItem* 的指针变成 ListItem* 指向的值 , 自然,第3个问号处,就返回第k个 ListItem 了.
firendlys 2012-06-26
  • 打赏
  • 举报
回复
也就是指针的一个最基本运用而已.
另外,提醒一下,以后代码,记得用 [code] 括起来,这样好看很多...
(就是点 字体颜色 和 插入超链接 中间的那个按钮 )


typedef ListItem *addr;
typedef struct indlist *List;
typedef struct indlist{
int n;
int maxsize;
addr *table;//将addr替换一下,就是 ListItem **table ,就是一个指向 ListItem* 的指针.指针的指针而已.
//一般情况下,使用指针的指针的目的是, table 指向一个 ListItem* 数组 , 这个数组里面每一个元素
//都指向一个真实的 ListItem .
// 事实上,你的这端代码正是这个意思,明白了这个,下面的2个问号也就不需要问了.

}Indlist;

List ListInit(int size)
{
List L=malloc(sizeof*L);
L->n=0;
L->maxsize=size;
L->table=malloc(size*sizeof(addr));//分配 ListItem* 的数组空间,这个数组总共有 size 个元素.
// 这个数组里面每一个元素都是 addr , 即ListItem* ,也就是指向 ListItem 的指针.
//额外说一句: 由于 addr 实际上是 ListItem* ,是一个指针,所以, sizeof(addr)=4 ...
return L;
}

ListItem ListRetrieve(int k,List L)
{
if(k<1||k>L->n)Error("out of bounds");
return *L->table[k-1];//返回一个ListItem. 还记得 table 实际上是 ListItem** 吧?
// 那么, L->table[k-1] 就可以找到 table这个指针指向的数组里面的 第 [k-1] 个元素(也是 ListItem指针)
// 然后,通过一个 * 运算,就得到实际的 ListItem 的值了.

}



就这么多了..

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧