其他分享
首页 > 其他分享> > 指针笔记----指针与数组01

指针笔记----指针与数组01

作者:互联网

回顾

#include <stdio.h>

int main()
{
    double s[5] = {90, 88, 79, 89, 88};
    double *p;

    p = s;//&s[0]

    printf("%f\n", s[2]);
    printf("%f\n", *(s + 2));
    printf("%f\n", p[2]);
    printf("%f\n", *(p + 2));
    
    return 0;
}

求一个数组中的最大值

#include <stdio.h>

double GetMax();

int main()
{
    double s[5] = {90, 88, 79, 89, 88};
    double *p, max;

    p = s;          //&s[0]
    max = GetMax(s, 5);

    printf("%.1f", max);

    return 0;
}

double GetMax(double *p, int n)
{
    int i;
    double maxnum;

    maxnum = p[0];      //maxnum = *p;
    for (i = 1; i < n; i++)
    {
        if (maxnum < p[i])  //if (maxnum < *(p + i))
        {
            maxnum = p[i];  //maxnum = *(p + i);
        }
    }

    return maxnum;
}

double GetMax(double p[], int n)如果这样写编译器会把double p[5]转化成double *p

GetMax函数也可以这样写:

double GetMax(double *p, int n)
{
    double maxnum;
    double *q;

    q = p;
    maxnum = p[0];      //maxnum = *p;
    for (; p < q + n; p++)
    {
        if (maxnum < *p) 
        {
            maxnum = *p; 
        }
    }

    return maxnum;
}

数组逆序

#include <stdio.h>

void exchange();

int main()
{
    double s[5] = {90, 88, 79, 89, 88};
    double *p;
    int i;

    p = s;          //&s[0]
    exchange(s, 5);

    for (i = 0; i < 5; i++)
    {
        printf("%.1f ", s[i]);
    }

    return 0;
}

void exchange(double p[], int n)
{
    int i, j = n - 1;

    while (i < j)
    {
        double t;

        t = p[i];
        p[i] = p[j];
        p[j] = t;
        i++, j--;
    }
}

标签:01,maxnum,int,double,----,88,printf,GetMax,指针
来源: https://blog.csdn.net/Genius_M/article/details/121789978