将不同的地址随机存储到数组里面,需要建立地址—数组索引index的关系,这里用了位操作
#include <stdio.h>
#include <stddef.h>
#include <string.h>
#include <malloc.h>
struct descriptor{
struct descriptor *free;
struct descriptor *link;
const void *ptr;
long size;
const char *file;
int line;
} *htab[2048];
int main(void)
{
void *ptr ;
ptr = malloc(sizeof(void *));
if (ptr == NULL)
{
printf("malloc failed\n");
return -1;
}
/* 2047 二进制是 111111 1111 & 操作10位以上是0, 根据 ptr低10位 index */
int n = ((unsigned long)ptr >> 3) & (sizeof(htab)/sizeof((htab)[0]) - 1);
printf("xxxx:%d\n", n);
free(ptr);
return 0;
}
说明:代码中着重关注
int n = ((unsigned long)ptr >> 3) & (sizeof(htab)/sizeof((htab)[0]) - 1); 方法;
因为sizeof(htab)/sizeof((htab)[0]) - 1 取数组最大下标,即2047,对应2进制 11 1111 1111
然后进行 & 操作,即对ptr 低10位进行 & 操作,值一定小于等于2047
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HGYc4fXJ-1651137644268)(htt]
ps://img-blog.csdnimg.cn/379edb6e0bc7463b9e8c752fe2558dc0.png)
由于ptr是随机的,所以每次执行结果也不一样