看代码看到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有什么区别???
都表示地址了,符号位还有存在必要吗???
具体怎么使用???
下面这个例子
#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;
}