嵌入式自学第四天
1、 地址传参可以改变实参的值。
例:交换两个数据
#include "stdio.h"
void jiaohuan(int *a,int *b)
{
int d=0;
d=*a;
*a=*b;
*b=d;
}
int main()
{
int a=10,b=20;
jiaohuan(&a,&b);
printf("%d,%d",a,b);
return 0;
}
例:统计字符串中小写字母个数,并把字符串中的小写字母转化成大写字母。
#include "stdio.h"
int zhuanhuan(char *p)
{
int num=0;
while(*p!='\0')
{
if(*p>='a'&&*p<='z')
{
num++;
*p=*p-32;
}
p++;
}
return num;
}
int main()
{
char a[]="hello word";//不能用char *p="hello word";这样的话属于常量不能被改变。
int num=0;
num=zhuanhuan(a);
printf("%d,%s\n",num,a);
return 0;
}
2、形参传递数组时 int data[] 传入数组 a;不对。应该用 int *data 传入a。数组传参除了字符串数组外其他数组要加一个参数,来提取数组的内容;
3、下图程序问题:因为str是局部变量,子程序执行完毕后自动释放,这时候在返回地址结果也是乱码。
(面试时如果给一段代码有指针,让你说明代码问题,99%可以回答内存有问题,执行结果不确定)
4、指针函数可返回值的条件:全局变量的地址,static变量的地址,字符串常量的地址,堆的地址(malloc)。
6、用指针函数去除字符空格
#include "stdio.h"
char * delate()
{
static char str[]=" hello word i a";
char *s1=str;
int i=0;
while(*s1!='\0')
{
if(*s1==' ')
s1++;
else
{
str[i]=*s1;
i++;
s1++;
}
}
str[i]='\0';
return str;
}
int main()
{
printf("%s\n",delate());
return 0;
}
7、字符串连接
#include "stdio.h"
char * delatear(char *p,char *q)
{
char * i=p;
while(*p!='\0')
{
p++;
}
while(*q!='\0')
{
*p=*q;
p++;
q++;
}
*p='\0';
return i;
}
int main()
{
char a[]="hello";
char b[]="word";
delatear(a,b);
printf("%s",a);
return 0;
}
8、用指针函数实现整数转字符串
#include "stdio.h"
char * delatear(int n)
{
int i,k=0,j=0,w,a;
static char q[20];
while(n)
{
i=n%10;
n=n/10;
q[k]=i+48;
k++;
}
q[k]='\0';
a=k-1;
while(j<a) //交换顺序
{
w=q[j];
q[j]=q[a];
q[a]=w;
j++;
a--;
}
return q;
}
int main()
{
int a=1234;
char *p;
p=delatear(a);
printf("%s\n",p);
return 0;
}
9、 利用递归实现n的阶乘运算
#include "stdio.h"
int de(int n)
{
if(n==1 || n==0)
{
return 1;
}
else
return n*de(n-1);
}
int main()
{
int a;
scanf("%d",&a);
printf("%d",de(a));
return 0;
}
10、函数指针
11、函数指针数组:相当于指针数组,不过内含函数指针。