至于什么for循环,什么定义变量我肯定不说了!我只想在这里说一下指针和结构体,因为在嵌入式中,我发现指针和结构体用得很多很多,简直就是一眼望去不是指针就是结构体。
关于什么指针的定义啊之类的我也不说了,那我要说什么呢?我要说的就是实例了,我会在这里说大量的实例。通过掌握大量的实例来提高c语言,我个人觉得这才是一个不错的选择。咱说做就做吧!
指针:
先讲几个概念性的东西吧,变量的指针就是变量的地址,存放地址的变量就是指针变量。
指针虽特殊,但是还是遵循所有的规则的。
一、不能通过改变形参的值,来改变实参的值。也就是调用函数的形参是不影响实参的。
假如真的想交换两个指针形参值的话,就直接交换呗!
二、*p表示的是p指向变量的值(切记*p就是一变量的值)。所以你想改变p指向的变量值,就操作*p吧!
三、p表示指向变量的地址值。
四、指针数组进行比较的时候还是有点不同的,就相比较的中间值也是指针,打印的时候不用在前面加*。
1、交换数据:
main()
{
int a,b;
int *pointer1,*pointer2;
pointer1=&a;
pointer2=&b;
swap(pointer1,pointer2);
getch();
}
swap(int *p1,int *p2)
{
Int temp;
Temp=*p1;
*p1=*p2;
*p2=temp;
}
2、利用指针实现数据排序:
main()
{
int a,b,c;
int *pointer1,*pointer2, *pointer3;
pointer1=&a;
pointer2=&b;
pointer3=&c;
exchange(pointer1,pointer2);
getch();
}
exchange(int *pt1, int *pt2, int *pt3);
{
if(*pt1<*pt2)
swap(pt1,pt2);
if(*pt1<*pt3)
swap(pt1,pt3);
if(*pt2<*pt3)
swap(pt2,pt3);
}
swap(int *p1,int *p2)
{
Int temp;
Temp=*p1;
*p1=*p2;
*p2=temp;
}
3、使用指针把数组元素输出来:
…
int a[10];
int i;
for(i=0;i<10;i++)
scanf(“%d”,&a[i]);
for(p=&a;p<(a+10);p++)
printf(“%d”,*p);
puts(“press any key to quit…”);
getch();
…
4、逆序存放数组函数:
inverte(int *x,int n) //x是数组,n是数组个数
{
int *p,temp,*i,*j,m=(n-1)/2;
i=x;
j=x+n-1;
p=x+m;
for(;i<=p;i++,j--)
{
temp=*i;
*i=*j;
*j=temp;
}
return 0;
}
5、查找数组中的最大值和最小值函数:
void max_min(int a[],int n,int *max,int *min)
{
int *p;
*max=*min=*a;
for(p=a+1;p if(*p>*max) *max=*p; else if(*p<*min) *min=*p; return 0; } 6、指向函数的指针比较大小: min(int a,int b) { if(a else return b; } void main() { int (*pmin)(); int a,b,m; pmin=min; m=(*pmin)(a,b); getch(); } 7、定义一个返回指针的函数: int *fun(int x,int y) 8、返回指针函数的查找的最大值: *Findmax(int *p,int n) { int i,*max; max=p; for(i=0;i { max=p+i; } return max; } void main() { int a[10]; max= Findmax(a,10); printf(“max:%d”,*max); getch(); } 9、字符串的连接函数: connect(char *s,char *t,char *q) { int i=0; for(;*s!=’\\0’;) { *q=*s; q++; s++; } for(;*t!=’\\0’;) { *q=*t; q++; t++; } *q=’\\0’; } 算法: x/2=1+1/3+1*2/3*5+1*2*3/3*5*7… double fun(double eps) { float n,t,pi,s; t=1; pi=1; n=1.0; s=1.0; while(fabs(s)>eps) { pi=pi+s; t=n/(2*n+1); s=*t; n++; } pi=2*pi; return pi; } 一、直接插入排序: 前后两个数相比较,小的放回前一点去,最小的那个就放在了s[0]了。 void insort(int s[],int n) { int I,j; for(i=2;i<=n;i++) { s[0]=s[i]; j=i-1; while(s[0] s[j+1]=s[j]; j--; } s[j+1]=s[0]; } } 数组的名字是一指针。 p2=&*p1; p1和p2指向a p1=&a &*p1相当于&a *&a相当于a 指针函数应用 main() { int a,b,*p; int *max(); p=max(a,b); } int *max(int x,int y) { if(...); return ; } 函数的名字就是代表函数的入口地址。 指向函数的指针: int (*p) () 应用: int max(…) { } int (*p)(); 指向函数的指针 p=max; main() { int max(); int (*p) ();定义指向函数的指针变量 int a,b,c; p=max; 指针变量赋值 c=(*p)(a,b);调用函数 } int max(x,y) { int z; if(x>y) … } a[10]; a++是错误的,a是常量地址。 (*p)++等于p指向的a值加1就是a[0]++ 想要终止一个宏定义#undef #if 大于1 编译程序段 #elif 大于1 编译程序段 #else 编译这一段 #endif #ifdef 有宏定义编译 编译程序段 #endif下载本文
{