勤能补拙,Expter

成都游戏Coder,记录游戏开发过程的笔记和心得!

一道指针笔试题

//已知结构体

struct node
{
    node 
* link;
    node 
* next;
}
;

struct test
{
    
int  a1;
    
int  a2;
    
//
    node *no;
    
int  aj;
    
//..
}
;
现在有一函数
int    Deal(node * link ,const int a);
假设知道link的地址,且知道link是一个test的一个对象(tmp)的地址。
现在求test对象tmp的地址。。

此题的关键就是看no前面有多少个int,然后减去偏移量即可。。
因为test的对齐字节为4个字节,然后no前面有(j-1)个int 变量。。

所以此题目及node *p = link;
                        test   *t = p - (j-1);        //因为对齐为4个字节
                        或者
                        int    add 得到p的地址。
                        则t的地址为 add-(j-1)*sizeof(int)


测试程序
# include <iostream>
# include 
<stdio.h>

struct node
{
    node 
* link;
    node 
* next;
}
;

struct test
{
    
int  a1;
    
int  a2;
    
//
    node *no;
    
int  aj;
    
//..
}
;

int main()
{
    test 
*= new test;  //
    node **= &(t->no);
    printf(
"t = %p\na = %p\n",t,a);//输出t,a的地址,
    printf("t = %p\n",a-2);//输入我们计算的地址

    
return 0;
}


posted on 2008-10-20 21:14 expter 阅读(899) 评论(1)  编辑 收藏 引用 所属分类: 面试笔记

评论

# re: 一道指针笔试题 2008-10-22 05:16 nick

根据题目条件
“现在有一函数 int Deal(node * link ,const int a);”
是不能确定test对象的地址的,因为要用函数实现,而函数接口只接受一个指针而不是指针的地址。  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理