Thread: Pointer to pointer

  1. #1
    Caution: Wet Floor
    Join Date
    May 2006
    Posts
    55

    Pointer to pointer

    Suppose a function f takes pointer to pointer to double A. B is a variable of the same type (declared in main() ). How do you (i) allocate space to A in f() and (ii) modify the contents of B via f()? I keep getting segmentation faults when trying to access elements of A in f() with things like *A[i] = (something). i is a loop variable.

    Code:
    void f(double **A) {
    
    int i = 0;
    /* ... */
    
    }
    
    int main(int argc, char *argv[]) {
    
            double **B=0;
    
            f(B);
    
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    (i) How do you ever allocate space for anything? Now the thing to worry about is that it is not possible, as you have it to change B in main, since B is passed by value not by pointer.
    (ii) If you haven't done (i), you can't do (ii).

  3. #3
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Just remember this: a pointer should always point to a valid address in memory. So if you have a double**, then both the double* that it points to and the double that that points to must be a valid address, if that makes sense. Here's an example using both real and dynamically allocated variables:

    Code:
    
    
    #include <stdio.h>
    #include <stdlib.h>
    
    int main( void )
    {
    	double
    		d1 = 1024, 
    		* dp1 = &d1, 
    		** dpp1 = &dp1, 
    		** dpp2;
    	dpp2 = malloc( sizeof( double* ) );
    	*dpp2 = malloc( sizeof( double ) );
    	**dpp2 = **dpp1;
    	printf( "Value: %f\n", **dpp2 );
    	free( *dpp2 );
    	free( dpp2 );
    	return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  2. Quick Pointer Question
    By gwarf420 in forum C Programming
    Replies: 15
    Last Post: 06-01-2008, 03:47 PM
  3. Parameter passing with pointer to pointer
    By notsure in forum C++ Programming
    Replies: 15
    Last Post: 08-12-2006, 07:12 AM
  4. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM