void*指针的由来

【转载】http://blog.csdn.net/mhjcumt/article/details/7355127

int a=1;

int *p = &a;

float *p1 = (float*)p;

pp1的值都是&a,但是*p是将&a地址中的值按照int型变量进行解释,而*p1则是将&a地址中的值按照float型变量进行解释。


鉴于指针之间这种灵活的强制类型转换的需求和出于简化代码的考虑,ANSI C引入了空指针即void*void指针又名万能指针,在现在的很多程序中,当参数不确定时就用万能指针代替,这一类的指针在线程\进程函数里特别常见。

ANSI C规定,void指针可以复制给其他任意类型的指针,其他任意类型的指针也可以复制给void指针,他们之间复制不需要强制类型转换。当然任何地址也可以复制给void型指针。我们在《网络编程》中经常会看到accept(socket, (struct sockaddr *)&saddr_c, &lenth)之类的语句在&saddr_c之前需要增加代码(struct sockaddr *)是因为当此函数被设计的时候ANSI C还没有提出void*的概念。所有的地址统一用struct sockaddr类型标识,该函数的第二个参数也是指向struct sockaddr类型的指针,此处是强制类型转换。

当然,在某些编译器中不同类型的指针也可以进行直接赋值,但一般情况下会给出类型不匹配的警告。要求程序员显示的给出指针强制类型转换可以提醒程序员小心使用指针,对于明确程序目的具有一定的好处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
请详细解析以下代码,罗列出其中涉及到的所有知识,并讲解每一行代码的由来:请详细解析以下代码,罗列出其中涉及到的所有知识,并讲解每一行代码的由来:#include <stdio.h> #include <stdlib.h> typedef struct tree////定义二叉树结点 { int data; struct tree* lchild; struct tree* rchild; }tree; typedef struct queue//定义队列结点 { tree* data; struct queue* next; }queue; typedef struct line//定义队列 { queue* front; queue* rear; }line; void rule(line* queue)//初始化队列 {queue->front=queue->rear=NULL;} int empty(line* queue)//判断队列是否为空 {return queue->front==NULL;} void in(line* queue, tree* node)//入队 { queue* qnode=(queue*)malloc(sizeof(queue)); qnode->data=node; qnode->next=NULL; if (queue->rear==NULL) {queue->front=queue->rear = qnode;} else { queue->rear->next = qnode; queue->rear = qnode; } } tree* out(line* queue)//出队 { if (queue->front==NULL) {return NULL;} else { tree* node = queue->front->data; queue* temp = queue->front; queue->front = queue->front->next; if(queue->front == NULL) {queue->rear = NULL;} free(temp); return node; } } void levelorder(tree* root)//按层次遍历二叉树 { if (root==NULL) {return;} line queue; rule(&queue); in(&queue,root); while(!empty(&queue)) { tree* node=out(&queue); printf("%d ",node->data); if(node->lchild != NULL) {in(&queue, node->lchild);} if(node->rchild != NULL) {in(&queue, node->rchild);} } } tree* create(int data)//创建二叉树结点 { tree* node=(tree*)malloc(sizeof(tree)); node->data=data; node->lchild=NULL; node->rchild=NULL; return node; } tree* create()//创建二叉树 { tree* root=create(1); root->lchild=create(2); root->rchild=create(3); root->lchild->lchild=create(4); root->lchild->rchild=create(5); root->rchild->lchild=create(6); root->rchild->rchild=create(7); return root; } int main() { tree* root=create(); printf("按层次遍历结果为: "); levelorder(root); return 0; }
05-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值