Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you declare a two dimensional array of pointers in C?

...without using typedef.

My boss claims he was once asked this in an interview, and when he gave his answer the interviewers told him he couldn't use typedefs because it was poor style.

Regardless, he likes to throw the question out at people just to see if they can get it right , usually at new programmer lunches. No one ever gets it right (especially without a pen and paper or computer handy). I want to be ready next time he tries to stump someone with it >:D

like image 326
Alex Avatar asked Jul 16 '09 08:07

Alex


1 Answers

2D array of pointers to what?

T *p[N][M];     // N-element array of M-element array of pointer to T
T (*p[N][M])(); // N-element array of M-element array of pointer to 
                // function returning T

If we're talking about pointers to 2D arrays, then things only get slightly more interesting:

T a[N][M];            // N-element array of M-element array of T
T (*p)[M] = a;        // Pointer to M-element array of T
T (**p2)[M] = &p;     // Pointer to pointer to M-element array of T
T (*p3)[N][M] = &a;   // Pointer to N-element array of M-element 
                      // array of T
T (**p4)[N][M] = &p3; // Pointer to pointer to N-element array of 
                      // M-element array of T

Edit: wait, I think I may be getting what you're after.

T *(*a[N])[M];        // a is an N-element array of pointer to M-element
                      // array of pointer to T

Edit: Now we get really silly:

T *(*(*a)[N])[M];     // a is a pointer to an N-element array of 
                      // pointer to M-element array of pointer to T

T *(*(*(*f)())[N])[M];  // f is a pointer to a function returning
                        // a pointer to an N-element array of pointer
                        // to M-element array of pointer to T

T *(*(*f[N])())[M];     // f is an N-element array of pointer to 
                        // function returning pointer to M-element 
                        // array of pointer to T

And for the pathologically insane:

T *(*(*(*(*(*f)())[N])())[M])(); // f is a pointer to a function 
                                 // returning a pointer to a N-element
                                 // array of pointer to function 
                                 // returning M-element array of
                                 // pointer to function returning
                                 // pointer to T

Typedefs are for wusses.

like image 172
John Bode Avatar answered Sep 19 '22 18:09

John Bode