1.定义一个"简单宏"或宏函数,实现两个数交换
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#define EXCHANGE(a,b,t) do {if(a>b) printf("%d %d\n",a,b); else { t=a;a=b;b=t;printf("%d %d\n",a,b);}}while(0)
int main(int argc, const char *argv[])
{
int a,b,t;
printf("please enter a and b:");
scanf("%d %d",&a,&b);
EXCHANGE(a,b,t);
return 0;
}
2.定义字符类型指针,指针指向n个连续堆区内存,输入,计算字符串长度
定义函数,实现内存申请
定义函数,计算字符串长度
定义函数释放内
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
// 定义字符类型指针,指针指向n个连续堆区内存,输入,计算字符串长度
char *memory(int size);
void str(char *p);
void LENGTH(char *p);
char *Memory(char *p);
int main(int argc, const char *argv[])
{ int size;
printf("please enter n:");
scanf("%d",&size);
char *p=memory(size);
printf("请输入字符串:");
str(p);
LENGTH(p);
p=Memory(p);
printf("成功释放内存\n");
return 0;
}
//定义函数,实现内存申请
char *memory(int size)
{
char *p=(char *)malloc(sizeof(char)*size);
if (p!=NULL)
{
printf("成功申请了%d大小的内存\n",size);
}
else
printf("申请内存失败");
return p;
}
//输入字符串
void str(char *p)
{
scanf("%s",p);
}
// 定义函数,计算字符串长度
void LENGTH(char *p)
{ int i;
for(i=0;p[i]!='\0';i++);
printf("字符串长度为%d\n",i);
}
// 定义函数释放内存
char* Memory(char *p)
{
free(p);
p=NULL;
return p;
}
思维导图