为什么数组指针打印不正确?

时间:2014-03-25 18:56:01

标签: c arrays pointers

我有一个功能(来自教程)

int* func(int *arr, int n){
    if(n==1 || n==0)
        return arr;
    else{
        int temp=arr[0];
        arr[0]=arr[n-1];
        arr[n-1]=temp;
        return func(++arr,n-2);
    } 
}

我干了它,并得到它将反转阵列,非常好。当我使用这段代码时,我得到了预期的结果

int x[]={1,2,3,4,5,6,7,8,9};
int i;
func(x,9);
for(i=0;i<9;i++) 
{
    printf("%d\n",x[i]);
}

但在使用以下代码时获取垃圾值

int x[]={1,2,3,4,5,6,7,8,9};
int* p;
p = func(x,9);
for(i=0;i<9;i++) 
{
    printf("%d\n",*(p+i));
}

指针弱,请与您解答。

3 个答案:

答案 0 :(得分:4)

你的问题是递归,而不是指针。可视化递归调用,返回的指针指向第5个元素:

func([1, 2, 3, 4, 5, 6, 7, 8, 9], 9) ->
func([2, 3, 4, 5, 6, 7, 8, 1], 7) ->
func([3, 4, 5, 6, 7, 2, 1], 5) ->
func([4, 5, 6, 3, 2, 1], 3) ->
func([5, 4, 3, 2, 1], 1) ->
[5, 4, 3, 2, 1]

来自评论:

  

这可能更好地说明了,我在打印之前增加了数组,因此您可以在递归调用中看到数组的样子:http://ideone.com/lzgEUX

答案 1 :(得分:1)

查看此代码:

#include <stdio.h>

int* func(int* arr, int n){
     if (n==1 || n==0)
        return arr; //remember this is the pointer we've been incrementing
     int temp = *arr; //instead of using bracket, I'm translating to pointer
     *arr = *(arr + n - 1); //arithmetic so it is more clear that we are 
     *(arr + n - 1) = temp; //merely manipulating a pointer to an int.
     return func(arr + 1, n - 2); //the pointer is incremented!
}


int main(int argc, char** args){
    int x[]={1,2,3,4,5,6,7,8,9}; //initialize our array
    int i=-4; //this is how much we need to offset the returned pointer
    int* p = func(x,9); //get the returned pointer
    for(;i<5;i++)
        printf("%d\n", *(p+i)); //print out each element of the array
    return 0;
}

答案 2 :(得分:1)

因此,当递归算法完成后,fund将返回指向arr中第5个元素的指针。因此,您的打印句子printf("%d\n",*(p+i));将从第5个元素开始打印,并向前打印9个字段。当它在第9个元素之后尝试打印元素时,您将获得垃圾值。

我试图像这样想象它,也许它会有所帮助:

arr = 0         // as non-relative pointer to element
temp = 1
arr[0] = 9
arr[8] = 1
func( arr=1, n = 7 )
    arr = 1
    temp = 2
    arr[1] = 8
    arr[7] = 2
    func ( arr=2, n = 5 )
        arr = 2
        temp = 3
        arr[2] = 7
        arr[6] = 3
        func ( arr=3, n = 3 )
            arr = 3
            temp = 4
            arr[3] = 6
            arr[5] = 4
            func ( arr=4, n = 1 )
                arr = 4
                n == 1
                return arr = 4
            return 4
        return 4
    return 4
return 4
p = 4