函数:一切没有修改内存的函数(所谓read mem 而又没返回数据的)都是没有实际价值的!!!
内容汇总
函数传参:
read:
func(constvoid *p, int len); //show_mem_bit(const void *p, int size);
func(constvoid *p); //strlen(const char *p)
func(typex); //add(int a, int b) //读一颗粒内存
write:
func(void*p, int len); //bzero(void *p, int size)
func(voidp[], int len); //rev_arr(int p[], intlen);
func(voidp[n]);
func(type*p); //写一颗粒内存
copy:
func(void*des, int len1, const void *src, int len2);
func(void*des, const void *src, int len); //memcpy(void *des, const void *src, int len);
func(void*des, const void *src); //strcpy(void*des, const void *src);
实际案例
两个值得交换,这里以字符串为例:
#include<stdio.h>
/*void swap(void *P,void *q,int size)//通用的类型,可以应用于各种的两种值交换
{
char*x=(char *)P;
char*y=(char *)q;
while(size--)
{
*x=*x ^ *y;
*y=*x ^ *y;
*x=*x ^ *y;
x++;
y++;
}
}*/
int swap_1(int *i,int *j)
{
*i=*i ^ *j;
*j=*i ^ *j;
*i=*i ^ *j;
}
char swap_2(char **n,char **m)
{
*m=(char *)((int)*n ^ (int)*m);
*n=(char *)((int)*n ^ (int)*m);
*m=(char *)((int)*n ^ (int)*m);
}
int main()
{
inta=100,b=10;
printf("a=%d,b=%d\n",a,b);
swap_1(&a,&b);
printf("a=%d,b=%d\n",a,b);
char*p="hello";
char*q="world";
printf("%s,%s\n",p,q);
swap_2(&p,&q);
printf("%s,%s\n",p,q);
return0;
}
Memcpy函数将一个字符串拷贝到另外一个字符串中
#include <stdio.h>
void show_int_arr(const int *p, int len)
{
while(len--)
printf("%d,",*p++);
printf("\n");
}
void mymemcpy(void *des, const void *src,int size)
{
char*p = (char*)des;
char*q = (char*)src;
while(size--)
*p++= *q++;
}
int main()
{
inta[] = {324,234,5,2345,34,6,4567,457,5687,5};
intb[] = {22,3,45,45,645,56,756};
show_int_arr(a,sizeof a/sizeof *a);
mymemcpy(a+3,b, 16);
show_int_arr(a,sizeof a/sizeof *a);
}
Return函数,搭车返回
#include <stdio.h>
int func()
{
inta = 0;
a|= 250<<8;
a|= 100<<16;
returna;
}
int main()
{
inta;
intb;
intc;
c= func();
a= (c & 0xff<<8) >>8;
b= (c & 0xff<<16) >>16;
printf("%d,%d\n", a, b);
}
将数的每个字节以二进制打印出来
#include <stdio.h>
static void show_char_bit(char c)
{
inti = 0;
for(;i<8;i++)
{
printf("%d",(c& 1<<7-i)?1:0);
}
printf("\n");
}
void show_bit(const void *p, int size)
{
char*tem = (char *)p;
while(size--)
show_char_bit(*tem++);
printf("\n");
}
int main()
{
inta = 0x2312;
show_bit(&a,sizeof a);
intx[] = {44,1234,12,34,1234,23,534,5,2345};
show_bit(x,sizeof x);
}