pointer to a pointer

This is a discussion on pointer to a pointer within the C Programming forums, part of the General Programming Boards category; Code: putchar(**(wp+1)); Hey guys with the above code why does that get the character 'c' from "cat" i dont understand ...

  1. #1
    Musicman - Canora
    Join Date
    Aug 2005
    Location
    Melbourne
    Posts
    252

    pointer to a pointer

    Code:
    putchar(**(wp+1));
    Hey guys with the above code why does that get the character 'c' from "cat" i dont understand the pointer to another pointer?

    Code:
    int main (void)
    {
    	char words[5][8] = {"the","cat","in","the","hat"};
    	char *wp[5];
    	int i=0;
    	
    	for(i=0; i<5; i++)
    	{
    		wp[i] = words[i];
    	}
    	
    	puts(*wp);
    	puts(*(wp+2));
    	puts(*(wp+3)+1);
    	putchar(**(wp+1));
    	
      return EXIT_SUCCESS;	
    }

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    wp is an array of pointers. This means wp can be viewed as a pointer to a pointer in one context or another.

    A variable just contains a value of a certain type. A pointer contains the address of a variable of a certain type. A pointer to a pointer contains an address of a pointer of a variable of a certain type. And so on.

    If wp is interpreted as a pointer, then it will be pointing at the first element of its array. This means it'll be resolved as the address of the string "the" from the array words, just as if you used wp[0] instead of (*wp). Since you're adding 1 to wp inside the function call, it'll be pointing to the next string, "cat", because (*(wp+1)) is just like having wp[1]. This means you only have a pointer to the string "cat". Dereferencing that one further means it'll also point at the first element of that array, which is the 'c' in "cat".

    I typed this up kind of quickly, so I might have hurried over some things I should have paid more attention to, but I hope this gives you an idea of how it works.

  3. #3
    Musicman - Canora
    Join Date
    Aug 2005
    Location
    Melbourne
    Posts
    252
    ahhh k kewl

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21