intptr_t和uintptr_t

看代码看到intptr_t和uintptr_t类型,有些不明白,查找后总结如下
参考http://www.cnblogs.com/Anker/p/3438480.html
这2个类型定义如下

/* Types for `void *' pointers.  */
#if __WORDSIZE == 64
#ifndef __intptr_t_defined
typedef long int		intptr_t;
#define __intptr_t_defined
#endif
typedef unsigned long int	uintptr_t;
#else
#ifndef __intptr_t_defined
typedef int	intptr_t;
#define __intptr_t_defined
#endif
typedef unsigned int uintptr_t;
#endif

上面分开64位机器非64位,64位上intptr_t、uintptr_t分别是long int和unsigned long int的别名,非64位是int、unsigned int的别名。

这和指针有什么关系?

如下表
在这里插入图片描述

64位机器上指针占8字节,long类型也占8字节,32位机器上指针占用4字节,int类型也占用4字节,所以intptr_t、uintptr_t才这样取别名就是为了能让整数类型与指针互相转换,且注意到为了兼容16位机器,在非64位机器的intptr_t、uintptr_t用int来取别名,而不是long。
总而言之就是:intptr_t是为了跨平台,其长度总是所在平台的位数,所以用来存放地址。
好处是啥???其实我们看明白,感觉是说不会解引用,能进行加减操作,更方便(我没理解到)

intptr_t、uintptr_t有什么区别???

UIntPtr和IntPtr的区别类似UInt32和Int32的区别,一个是无符号的32位整数(本质是一个地址),一个是有符号的32位整数。UInt32能表示更大的值,代价是没有符号位
都表示地址了,符号位还有存在必要吗???

具体怎么使用???

下面这个例子

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>

#define ID_STR_LEN   12
#define NAME_STR_LEN 10

typedef struct student
{
    char id[ID_STR_LEN];
    char name[NAME_STR_LEN];
    uint8_t age;
}student;

student * create_student()
{
    student *stu = (student *)malloc(sizeof(student));
    if (stu == NULL)
    return NULL;
    memset(stu, 0, sizeof(student));
    return stu;
}

void *free_student(student *stu)
{
    if (stu)
    free(stu);
}

static void init_student(student * stu)
{
    assert(stu);
    const char *id = "2013112210";
    const char *name = "Anker";
    uint8_t age = 21;
    memcpy(stu->id, id, strlen(id));
    memcpy(stu->name, name, strlen(name));
    stu->age = age;
}

static int handle_student(intptr_t handle)
{
    if (handle == 0)
    {
    return -1;
    }
    student *stu = (student*)handle;
    printf("id: %s\n", stu->id);
    printf("name: %s\n", stu->name);
    printf("age: %u\n", stu->age);
    return 0;
}

int main()
{
    student *stu;
    stu = create_student();
    init_student(stu);
    //将指针转换为intptr_t类型
    intptr_t handle = (intptr_t)stu;
    handle_student(handle);
    free_student(stu);
    return 0;
}
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值