我们可以将数组变量添加到整数吗?

时间:2016-07-02 14:27:59

标签: c++ c arrays sorting

这是一个程序,用于查找两个已排序数组的中位数。

基于分而治之的有效解决方案,用于查找两个相同大小的排序数组的中位数。

    #include<bits/stdc++.h>
    using namespace std;

    int median(int [], int); /* to get median of a sorted array */

    /* This function returns median of ar1[] and ar2[].
    Assumptions in this function:
    Both ar1[] and ar2[] are sorted arrays
    Both have n elements */
    int getMedian(int ar1[], int ar2[], int n)
    {
        /* return -1 for invalid input */
        if (n <= 0)
            return -1;
        if (n == 1)
            return (ar1[0] + ar2[0])/2;
        if (n == 2)
            return (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1])) / 2;

        int m1 = median(ar1, n); /* get the median of the first array */
        int m2 = median(ar2, n); /* get the median of the second array */

        /* If medians are equal then return either m1 or m2 */
        if (m1 == m2)
            return m1;

        /* if m1 < m2 then median must exist in ar1[m1....] and
            ar2[....m2] */
        if (m1 < m2)
        {
            if (n % 2 == 0)
            {

                return getMedian(ar1 + n/2 - 1, ar2, n - n/2 +1);

            }
            return getMedian(ar1 + n/2, ar2, n - n/2);
        }

        /* if m1 > m2 then median must exist in ar1[....m1] and
            ar2[m2...] */
        if (n % 2 == 0)
            return getMedian(ar2 + n/2 - 1, ar1, n - n/2 + 1);
        return getMedian(ar2 + n/2, ar1, n - n/2);
    }

    /* Function to get median of a sorted array */
    int median(int arr[], int n)
    {
        if (n%2 == 0)
            return (arr[n/2] + arr[n/2-1])/2;
        else
            return arr[n/2];
    }

    /* Driver program to test above function */
    int main()
    {
        int ar1[] = {1, 2, 3, 6};
        int ar2[] = {4, 6, 8, 10};
        int n1 = sizeof(ar1)/sizeof(ar1[0]);
        int n2 = sizeof(ar2)/sizeof(ar2[0]);
        if (n1 == n2)
            printf("Median is %d", getMedian(ar1, ar2, n1));
        else
            printf("Doesn't work for arrays of unequal size");
        return 0;
    }

我的问题是如何将数组变量添加到整数。我的意思是当我们在getmedian函数调用中这样做(ar1 + n / 2 - 1)时它是指内存吗?

1 个答案:

答案 0 :(得分:0)

在表达式中,数组指示符被隐式转换为指向其第一个元素的指针。向指针添加整数将再次获得指针。它被称为指针算法。

因此,例如,如果你有一个数组

int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
const size_t N = sizeof( a ) / sizeof( *a );

然后表达

a + N / 2 

将指向数组的第六个元素。

这是一个示范程序

#include <stdio.h>

int main(void) 
{
    int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    const size_t N = sizeof( a ) / sizeof( *a );

    for ( size_t i = 0; i < N; i++ ) printf( "%p: %d\n", a + i, *( a + i ) );

    return 0;
}

它的输出可能看起来像

0xbfd3d9c8: 0
0xbfd3d9cc: 1
0xbfd3d9d0: 2
0xbfd3d9d4: 3
0xbfd3d9d8: 4
0xbfd3d9dc: 5
0xbfd3d9e0: 6
0xbfd3d9e4: 7
0xbfd3d9e8: 8
0xbfd3d9ec: 9

同样声明为数组的函数参数也会调整为指针。例如,这些函数声明

int median(int a[100], int n); 
int median(int a[10], int n); 
int median(int a[], int n);
int median(int *a, int n);  

是等效的,并声明相同的一个函数。