免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1917 | 回复: 5
打印 上一主题 下一主题

[C] 求教一个困扰我很久的void*问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-02-28 11:51 |只看该作者 |倒序浏览
#include<stdio.h>
void *  test(void *a)
{
int temp=3;
(int *)a=temp;
return a;
}
//void main(void)  //in GCC this is wrong
main()
{
int  **b;
test(*b);
int tt=(int )test(*b);              //why isn't "int tt=(int *)test(*b);"
printf("%d\n",**b);
printf ("(int*)tt=%d\n",tt);
}

运行输出结果是
0
(int*)tt=3


请问一下为什么*a不能传递数值?

论坛徽章:
0
2 [报告]
发表于 2008-02-28 12:05 |只看该作者
void *  test(void *a)
{
int temp=3;
(int *)a=temp;
return a;
}

把这个函数改成
void *  test(void *a)
{
int temp=3;
memcpy(a, &temp, sizeof(int));
return a;
}

试试,因为 void *a是引用传递

论坛徽章:
0
3 [报告]
发表于 2008-02-28 12:50 |只看该作者
按照nmzqzw兄弟的做法,结果是
3
Segmentation fault

论坛徽章:
0
4 [报告]
发表于 2008-02-28 12:53 |只看该作者
按你的程序做法需要在这个函数里需要malloc空间的,

论坛徽章:
0
5 [报告]
发表于 2008-02-28 13:07 |只看该作者
#include<stdio.h>
void *  test(void *a)
{
        int temp=3;
        int *p = (int *)a;
        *p = temp;
        return a;
}
//void main(void)  //in GCC this is wrong
main()
{
int num = 5;
int *tmp = &num;
int  **b = &tmp;
test(*b);
int *p = (int *)test(*b);
int tt=*p;              //why isn't "int tt=(int *)test(*b);"
printf("%d\n",**b);
printf ("(int*)tt=%d\n",tt);
}

输出结果:
3
(int*)tt=3

论坛徽章:
0
6 [报告]
发表于 2008-02-28 17:27 |只看该作者
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP