Passing and returing a pointer in function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nidhigarg
    New Member
    • Oct 2007
    • 1

    Passing and returing a pointer in function

    I am trying to pass a pointer of an array in function. In function, i am trying to reverse the array elements.After that, pointer will return to main() function. In rev() function it prints perfectly alright but in main() it only print 1st element of array and then print some garbage value.Please solve my problem.
    Code:
    #include<stdio.h>
    #include<conio.h>
    int *rev(int *p);
    main()
    {
    int a[5],*x,i,a2[5],*t;
    clrscr();
    x=a;
    //t=a2;
    printf("\n enter the no");
    for(i=0;i<=4;i++)
    
    scanf("%d",(x+i));
    t=rev(x);
    for(i=0;i<=4;i++,t++)
    printf("\n%d",*t);
    getch();
    }
    int *rev(int *p)
    {
    int *r,i,a1[5],j;
    r=a1;
    p=p+4;
     for(i=0;i<=4;i++,r++,p--)
    {
    r=p;
    printf("\n%d",*r);
     }
    r=r-5;
    printf("\n%d",*r);
     return r;
      }
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Originally posted by nidhigarg
    [CODE=c]

    int *rev(int *p)
    {
    int *r,i,a1[5],j;

    r=a1;
    p=p+4;

    for(i=0;i<=4;i+ +,r++,p--)
    {
    r=p;
    printf("\n%d",* r);
    }

    r=r-5;
    printf("\n%d",* r);

    return r;
    }
    [/CODE]
    You problem is here in the function rev, you return r and r points to the array a1. However a1 is an automatic storage class variable which means it is created on the program stack and that in turn means it is deleted when the execution returns from the function so all the data in it is lost.

    I would suggest that rev should take 2 pointers, 1 to the array with the data and 1 to the array to store the reversed data. You probably ought to pass the number of elements in the array into rev as well rather than assuming it is 5.

    Comment

    Working...