figurassa figurassa - 1 year ago 86
C Question

C pointers : pointing to an array of fixed size

This question goes out to the C gurus out there:

In C, it is possible to declare a pointer as follows:

char (* p)[10];

.. which basically states that this pointer points to an array of 10 chars. The neat thing about declaring a pointer like this is that you will get a compile time error if you try to assign a pointer of an array of different size to p. It will also give you a compile time error if you try to assign the value of a simple char pointer to p. I tried this with gcc and it seems to work with ANSI, C89 and C99.

It looks to me like declaring a pointer like this would be very useful - particularly, when passing a pointer to a function. Usually, people would write the prototype of such a function like this:

void foo(char * p, int plen);

If you were expecting a buffer of an specific size, you would simply test the value of plen. However, you cannot be guaranteed that the person who passes p to you will really give you plen valid memory locations in that buffer. You have to trust that the person who called this function is doing the right thing. On the other hand:

void foo(char (*p)[10]);

..would force the caller to give you a buffer of the specified size.

This seems very useful but I have never seen a pointer declared like this in any code I have ever ran across.

My question is: Is there any reason why people do not declare pointers like this? Am I not seeing some obvious pitfall?

Answer Source

I would like to add to AndreyT's answer (in case anyone stumbles upon this page looking for more info on this topic):

As I begin to play more with these declarations, I realize that there is major handicap associated with them in C (apparently not in C++). It is fairly common to have a situation where you would like to give a caller a const pointer to a buffer you have written into. Unfortunately, this is not possible when declaring a pointer like this in C. In other words, the C standard (6.7.3 - Paragraph 8) is at odds with something like this:

   int array[9];

   const int (* p2)[9] = &array;  /* Not legal unless array is const as well */

This constraint does not seem to be present in C++, making these type of declarations far more useful. But in the case of C, it is necessary to fall back to a regular pointer declaration whenever you want a const pointer to the fixed size buffer (unless the buffer itself was declared const to begin with). You can find more info in this mail thread: link text

This is a severe constraint in my opinion and it could be one of the main reasons why people do not usually declare pointers like this in C. The other being the fact that most people do not even know that you can declare a pointer like this as AndreyT has pointed out.
