Reputation: 5762
I have a function(from a tutorial)
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);
}
}
I dry run it and get that it will reverse the array, very good. I'm getting the result as expected when I using this piece of code
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]);
}
But getting garbage value when using below code
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));
}
Weak in pointer please explain with you answer.
Upvotes: 1
Views: 142
Reputation: 4302
So when the recursive algorithm is done, fund will return a pointer to the 5th element in arr. So your print-sentence: printf("%d\n",*(p+i));
, will start printing from the 5th element, and 9 fields forward. When it tries print elements after the 9th element, you will get garbage values.
I tried to visualize it like this, maybe it helps:
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
Upvotes: 1
Reputation: 1975
Your problem is with recursion, not pointers. Visualizing the recursive calls, the returned pointer points to the 5th element:
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]
From the comments:
This might illustrate it better, I incremented the array before printing, so you can see what the array looks like in the recursive call: http://ideone.com/lzgEUX
Upvotes: 4
Reputation: 1753
Check out this code:
#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;
}
Upvotes: 1