1.定义一个“简单宏”或宏函数,实现两个数的交换
#include <stdio.h>
#include <stdlib.h>
#define CHANGE(x,y) ({\
x = x + y;\
y = x - y;\
x = x - y;\
})
int main()
{
int a = 2, b = 5;
printf("a = %d b = %d\n", a, b);
CHANGE(a, b);
printf("change a & b\n");
printf("a = %d b = %d\n", a, b);
return 0;
}
2.定义字符类型的指针,指针指向n个连续堆区内存,输入,计算字符串长度
定义函数,实现内存申请
定义函数,计算字符串长度
定义函数,释放内存
#include <stdio.h>
#include <stdlib.h>
char* create(int n)
{
char* p = (char*)malloc(sizeof(char) * n);
if (NULL == p)
{
return NULL;
}
return p;
}
void length(int n, char* p)
{
int i;
for (i = 0; '\0' != *(p + i); i++);
printf("length = %d\n", i);
}
void freePtr(char* p)
{
if (NULL == p)
{
return;
}
free(p);
p = NULL;
}
int main()
{
int n;
scanf("%d", &n);
char* p = create(n);
if (p == NULL)
{
printf("初始化内存失败\n");
return -1;
}
scanf("%s", p);
length(n, p);
freePtr(p);
return 0;
}
3.思维导图