August 1st, 2013, 09:42 AM
Declaration of pointer to pointer ??
I have an array of pointers, each one pointing to a struct called Book:
And i'm using a SWAP function that swaps the order of two pointers, each of them pointing to another pointer which points to a book.
Book *array; /*The array of pointers*/
Inside the swap function i use a POINTER TO A POINTER TO A BOOK: *ppbook-->*BookPtr--->Book because otherwise only the values are swapped and nothing happens.
typedef Book *BookPtr; /*BookPtr is now of type: pointer to Book struct*/
void swap(BookPtr *ppbook1, BookPtr *ppbook2)
BookPtr temp= *ppbook1;
My question is: In the book i'm learning from they declare the "temp" from the swap function to be a "BookPtr" type !
But BookPtr is a pointer to struct, when it actually should be A POINTER TO A POINTER TO STRUCT ??
Shouldn't they declare(?):
I mean so "temp" would be declard to store a pointer to a pointer to Book, instead of just pointer to Book ?
typedef BookPtr *pp;
AND THEN: pp temp= *ppbook1;
August 1st, 2013, 10:25 AM
Think though the levels of indirection methodically.
You have an array of Book pointers. You want to be able to swap pointers in that array, right? So when you pass a pointer to one of those pointers (eg, you'd pass &array to swap), you'd have a pointer to a pointer. That means that the parameters of that function would have to be pointers to pointers, or Book**. Within the function, you're swapping pointers to Book, Book*, which you accomplish with the Book** parameters by dereferencing them, removing one level of indirection.
All you're doing with that typedef is to apply some syntactic sugar that hides one level of indirection. The function looks right to me.
August 1st, 2013, 10:37 AM
Wait, so temp is declard to hold the data WHICH IS POINTED BY "ppbook1" ? (the data=which is a regular pointer)
I think i see what you mean :cheers:
August 1st, 2013, 11:45 AM
August 1st, 2013, 01:14 PM
I'm going to read it.