Thread: Pointer to structure

  1. #1
    Registered User
    Join Date
    Oct 2022
    Posts
    92

    Pointer to structure

    Can someone confirm if I am thinking right. If I want to change value of pointer so I think I need to pass address of pointer not the copy of pointer

    Code:
    #include<stdio.h>
    
    #include<stdlib.h>
    
    
    struct s
    {
    	int var;
    };
    
    
    int main ()
    {
    	struct s *sp = NULL;
    	
    	foo(&sp); // Pass address of sp to function foo
    	foo(sp);  // Pass copy of sp  to function foo
    	
    	return 0;
    }

  2. #2
    Registered User
    Join Date
    Feb 2022
    Location
    Canada, PEI
    Posts
    103
    Yes that is correct.. If you need to change the value of the pointer variable(via a function call), then you pass the address of the variable pointer.

  3. #3
    Registered User
    Join Date
    Oct 2022
    Posts
    92
    Quote Originally Posted by G4143 View Post
    Yes that is correct.. If you need to change the value of the pointer variable(via a function call), then you pass the address of the variable pointer.
    Why there is need to declare double pointer as argument, not just pointer to structure to change variable sp

  4. #4
    Registered User
    Join Date
    Feb 2022
    Location
    Canada, PEI
    Posts
    103
    Quote Originally Posted by Kittu20 View Post
    Why there is need to declare double pointer as argument, not just pointer to structure to change variable sp
    You pass a pointer to a pointer because you need to pass the original variable address which is a pointer... Clear as mud right?

    It all comes down to what is passed to the function "copied" and what the copied values represent.

    The biggest hurdle here is understanding that C functions pass by value(i.e. it copies the value).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 08-04-2017, 07:42 AM
  2. Replies: 2
    Last Post: 04-26-2011, 10:40 PM
  3. Referencing pointer inside a structure pointer
    By SasDutta in forum C Programming
    Replies: 2
    Last Post: 11-11-2010, 11:33 AM
  4. Replies: 9
    Last Post: 06-13-2009, 02:31 AM

Tags for this Thread