指针入门到精通二
1.指针数组与数组指针
//指针数组
#include <stdio.h>
int main()
{
char* PointerArr[5] = { "你","是","学","生","!" };
for (int i = 0; i < 5; i++)
printf("%s", PointerArr[i]);
printf("\n");
return 0;
}
//数组指针
#include <stdio.h>
int main()
{
char Arr[][4] = { "妹","妹","你","坐","船","头","!" };
char(*pi)[4] = Arr;
for (int i = 0; i < 7; i++)
printf("%s", *(pi + i));
printf("\n");
return 0;
}
2.动态内存分配详解
/*
非静态的局部变量是分配在内存中的动态存储区。
对内存的动态分配是通过系统提供的库函数来实现的。4个函数malloc,calloc,free,realloc
malloc函数:void *malloc(unsigned int size);malloc(100);
calloc函数:void *calloc(unsigned n,unsigned size);p=calloc(50,4)
free函数:void free(void *p);free(p);
realloc函数:void *realloc(void *p,unsigned int size);realloc(p,50);
这4个函数应用时,要声明头文件 #include <stdlib.h>
编程实现:开辟动态自由存储区域,存储5个学生成绩,输出不及格的分数
*/
#include <stdio.h>
#include <stdlib.h>
void CheckScore(int *ps)
{
printf("\n不及格的分数如下:\n");
for (int i = 0; i < 5; i++)
if (ps[i] < 60)
printf("%5d", ps[i]);
printf("\n");
}
int main()
{
int *ps;
ps = (int*)malloc(5 * sizeof(int));
printf("\n请输入学生的成绩:\n");
for (int i = 0; i < 5; i++)
scanf_s("%d", ps + i);
printf("\n学生的成绩为:\n");
for (int i =0; i < 5; i++)
printf("%4d", *(ps + i));
printf("\n");
CheckScore(ps);
return 0;
}