Thread: pass pointer into function and return pointer from function

  1. #1
    Registered User
    Join Date
    Feb 2022
    Posts
    73

    pass pointer into function and return pointer from function

    I am trying to write code in which i want to pass pointer into function and return pointer from function

    This is my test code

    Code:
     #include<stdio.h>
    #include<stdlib.h> 
    
    
    int *foo( int *ptr )
    {
       int *qtr = malloc (sizeof(*qtr));
       
        if (qtr == NULL) 
        { 
            printf("Memory not allocated.\n"); 
            return 0; 
        } 
       
       qtr = ptr;
       
       return qtr;
    }
        
    int main()
    {
        
        int *ptr = malloc (sizeof(*ptr));
    
    
        if ( ptr == NULL ) 
        { 
            printf("Memory not allocated.\n"); 
            return 1; 
        }     
        
        ptr = foo ( ptr );    
        
        return 0;    
    }
    I am trying figure out what happen when we pass pointer into function and return pointer from function by printing memory location value. I don't have any idea how to make furthrt progress

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Well line 15 is a memory leak of the memory you allocated at line 7.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Cant pass NULL pointer to the function
    By Oscar Wong in forum C Programming
    Replies: 1
    Last Post: 03-22-2012, 09:04 AM
  2. Replies: 10
    Last Post: 09-15-2010, 05:38 AM
  3. how to pass function pointer as arg in c++
    By umen242 in forum C++ Programming
    Replies: 13
    Last Post: 10-21-2008, 02:09 AM
  4. Pass pointer to function
    By markucd in forum C++ Programming
    Replies: 3
    Last Post: 01-07-2006, 01:18 PM
  5. Replies: 6
    Last Post: 11-29-2004, 08:50 AM

Tags for this Thread