不同的struct之间可以根据其内存的存放规则进行强制类型转换。
实例1:
实例2
2.结构体变量的大小动态变化
3.快速计算一个数字包含几位
原理:x &=(x-1) deletes the rightmost 1-bit in x.
实例1:
#include <stdio.h>
#include <string.h>
struct addr
{
int ip;
char host_name[100];
};
struct addr_in
{
int ip;
char host_name[100];
int other;
};
int main()
{
addr_in local;
local.ip=123;
strcpy(local.host_name,"www");
addr* ad = (addr*)&local;
printf("%s\n",ad->host_name);
return 0;
}
实例2
#include <stdio.h>
#include <string.h>
struct addr
{
int ip;
char host_name[100];
};
struct addr_in
{
addr in_addr;
int size;
};
int main()
{
addr_in local;
local.in_addr.ip=123;
strcpy(local.in_addr.host_name,"www");
addr *ad = (addr*)&local;
printf("%d %s",ad->ip,ad->host_name);
return 0;
}
2.结构体变量的大小动态变化
#include <stdio.h>
#include <stdlib.h>
typedef struct addr
{
int size;
int in_addr[0];
} ADDR;
int main(void)
{
ADDR *adr;
int i;
adr = (ADDR *)malloc(sizeof(int)*100);
for(i=0;i<99;i++) {
adr->in_addr[i] = i;
printf("%d ", adr->in_addr[i]);
}
return 0;
}
3.快速计算一个数字包含几位
原理:x &=(x-1) deletes the rightmost 1-bit in x.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int bitcount(int x)
{
int count = 0;
while(x)
{
x &= (x-1);
count++;
}
return count;
}
int main()
{
srand( (unsigned)time( NULL ) );
int a = rand();
printf("%d has %d bits",a,bitcount(a));
return 0;
}