知识点:学会运用数组指针
思路:
定义指向整型数组的指针变量,将a[0]的地址赋给指针变量
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 0, 9 };
int *p = a;
定义最大值最小值为max,min.首先将a[0]的值赋给max,利用循环找出数组中的最大值,记住他的位置与第一个位置互换
max = *p;
for (i = 0; i < 10; i++)
{
if (max < *(p + i))
{
max = *(p + i);
n = i;
}
}
max = *p;
*p = *(p + n);
*(p + n) = max;
同理 将a[0]的值赋给min,利用循环找出数组中的最小值,记住他的位置与最后一个位置互换
min = *p;
for (i = 0; i < 10; i++)
{
if (min>*(p + i))
{
min = *(p + i);
m = i;
}
}
min = *(p + 9);
*(p + 9) = *(p + m);
*(p + m) = min;
整理可得:
#include<stdio.h>
#include<windows.h>
int main()
{
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 0, 9 };
int max = 0, min = 0, i, n, m;
int *p = a;
max = *p;
for (i = 0; i < 10; i++)
{
if (max < *(p + i))
{
max = *(p + i);
n = i;
}
}
max = *p;
*p = *(p + n);
*(p + n) = max;
min = *p;
for (i = 0; i < 10; i++)
{
if (min>*(p + i))
{
min = *(p + i);
m = i;
}
}
min = *(p + 9);
*(p + 9) = *(p + m);
*(p + m) = min;
for (i = 0; i < 10; i++)
printf("%d", a[i]);
system("pause");
return 0;
}
输出结果