Thread: local variables and stack

  1. #1
    Registered User
    Join Date
    Apr 2015
    Posts
    180

    local variables and stack

    I read the concept that variables are only alive for the time execution of the program. Once the functions finish it's job the variables are destroyed. If it is indeed like that then why is it that code like example below works?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int *find_largest(int a[], int n)
    {
        int i, *max;
        max=&a[0];
        for(i=1;i<n;i++)
        {
            if(a[i]>*max)
            {
                *max=a[i];
            }
        }
        return max;
    }
    
    
    int main()
    {
    
    
        int *ptr;
        int V[]={9, 18, 31, 40, 42};
        ptr = find_largest(V, 5);    
        printf("Largest = %d\n",*ptr);
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    What exactly do you find puzzling? If you are puzzled by the fact that one can return a local pointer, then look at the fact that you got the pointer to point to an element in the array in declared in main.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 11-21-2013, 10:00 AM
  2. Local variables popped from stack or is it ?
    By trish in forum C Programming
    Replies: 7
    Last Post: 07-04-2011, 01:42 PM
  3. Replies: 6
    Last Post: 12-02-2009, 08:47 AM
  4. local stack variables
    By Amyaayaa in forum C++ Programming
    Replies: 25
    Last Post: 10-07-2008, 01:13 PM
  5. local variables
    By Unregistered in forum C Programming
    Replies: 14
    Last Post: 03-20-2002, 02:55 PM