初学C\C++——指针与数组(2)

时间:2019-02-16
本文章向大家介绍初学C\C++——指针与数组(2),主要包括初学C\C++——指针与数组(2)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.1打印数组元素

int buf[10] = { 24,43,65,23,1,22,74,33,45,99 }

//通过指针来遍历输出
void MyPrint(int buf[])
{
    for(int i = 0;i < 10; i++)
    {
        printf("%d\n",*(buf + i));
    }
}

1.2数组逆置

int array[10] = { 24,43,65,23,1,22,74,33,45,99 };


void InverseOperation(int array[])
{
    int *start = &array;
    int *end = start + 9;
    
    while( start < end )
    {
        int temp = *start;
        *start = *end;
        *end = temp;
        
        start++;
        end--;
    } 
}

1.2求数组最大值

int array[10] = { 24,43,65,23,1,22,74,33,45,99 };

int Max(int *s)
{
    int value = *s;
    for(int i = 0; i < 10; i++)
    {
        if(*(s + i) > value)
            value = *(s + i)
    }
    return value;
}

1.3求数组第二大值

int array[10] = { 24,43,65,23,1,22,74,33,45,99 };

int SMax(int *s)
{
    int max = *s;
    int s_max = *(s + 1);
    
    for(int i = 2; i < 10; i++)
    {
        if(max < *(s + i))//如果比最大值还大,那么当前值存放到最大值max中,而之前max的值存放到s_max中
        {
            max = *(s + i);
            s_max = max;
        }
        else if(max > *(s + i) && *(s +i) > s_max)//当前的值小于最大值,并且大于第二大值,则存放到s_max中
        {
            s_max = *(s +i);
        }
    }
    
    return s_max;
}

1.4求数组排序(冒泡)

int array[10] = { 24,43,65,23,1,22,74,33,45,99 };

void bubble(int *s)
{
    for(int i = 0; i < 10; i++)
    {
        for(int j = 1; j < 10 -j;j++ )
        {
            if(*(s + j) < *(s + j-1))
            {
                int temp = *(s + j);
                *(s + j) = *(s + j-1);
                *(s = j-1) = temp;
            }                        
        }
    }
}