Thread: Pointer to Pointer and Pointer to Pointer to Pointer

  1. #1
    Registered User
    Join Date
    May 2010

    Pointer to Pointer and Pointer to Pointer to Pointer

    I understand pointers much better now and even **p, ***p, ****p, etc. However, it is passing a pointer to a function such as int makeargv(... char ***argvp) and returning the address to the 3 layers of pointing.

    I do not fully understand the following:

    int allocstr(char **retptr)
    	char *p = "Hello";
    	*retptr = p;
    	return 1;
    in particular why retptr = &p returns null to me and *retptr = p returns address of H.

    I would love to read a detailed explanation from this forums please and help finalize my understanding of pointers and functions.

    Thank you

  2. #2
    Registered User
    Join Date
    Jul 2010
    p holds the address of the first character in the string literal, in this case "H".

    p [Address of string literal] -> ["H....]

    retptr is a pointer that pointer to a character pointer so when it is dereferenced, *retptr is a character pointer and is assigned the value in p ( the address of the first character of the string literal )

    retptr [Address of *retptr ] ->*retptr [Address of string literal] -> ["H.....]

    I should point out however ( no pun intended ) that you cannot create such a function as you would be assigning the address of a local variable which will be destroyed when the function exits ( *retptr will then point to invalid memory ). If you wish a function like this, you will need to use malloc instead:

    int allocstr(char **retptr)
            char temp[] = "Hello";
    	*retptr = malloc(sizeof(char)*(strlen(temp)+1));
    	return 1;
    And what do you mean retptr = &p returns null to you? I do not see this code?
    Last edited by CSaw; 07-19-2010 at 07:04 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  3. Quick Pointer Question
    By gwarf420 in forum C Programming
    Replies: 15
    Last Post: 06-01-2008, 03:47 PM
  4. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM
  5. file pointer
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 10-11-2001, 03:52 PM