26
votes

When working with arrays and pointers in C, one quickly discovers that they are by no means equivalent although it might seem so at a first glance. I know about the differences in L-values and R-values. Still, recently I tried to find out the type of a pointer that I could use in conjunction with a two-dimensional array, i.e.

int foo[2][3];
int (*a)[3] = foo;

However, I just can't find out how the compiler "understands" the type definition of a in spite of the regular operator precedence rules for * and []. If instead I were to use a typedef, the problem becomes significantly simpler:

int foo[2][3];
typedef int my_t[3];
my_t *a = foo;

At the bottom line, can someone answer me the questions as to how the term int (*a)[3] is read by the compiler? int a[3] is simple, int *a[3] is simple as well. But then, why is it not int *(a[3])?

EDIT: Of course, instead of "typecast" I meant "typedef" (it was just a typo).

8
You might be interested in reading cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/pointer.html.sand
Only a very small portion of the provided link is related to my original question which was already answered in detail by the answers below. Thanks for your answer anyway!!fotNelton

8 Answers

21
votes

First, you mean "typedef" not "typecast" in your question.

In C, a pointer to type T can point to an object of type T:

int *pi;
int i;
pi = &i;

The above is simple to understand. Now, let's make it a bit more complex. You seem to know the difference between arrays and pointers (i.e., you know that arrays are not pointers, they behave like them sometimes though). So, you should be able to understand:

int a[3];
int *pa = a;

But for completeness' sake: in the assignment, the name a is equivalent to &a[0], i.e., a pointer to the first element of the array a. If you are not sure about how and why this works, there are many answers explaining exactly when the name of an array "decays" to a pointer and when it does not:

I am sure there are many more such questions and answers on SO, I just mentioned some that I found from a search.

Back to the topic: when we have:

int foo[2][3];

foo is of type "array [2] of array [3] of int". This means that foo[0] is an array of 3 ints, and foo[1] is an array of 3 ints.

Now let's say we want to declare a pointer, and we want to assign that to foo[0]. That is, we want to do:

/* declare p somehow */
p = foo[0];

The above is no different in form to the int *pa = a; line, because the types of a and of foo[0] are the same. So, we need int *p; as our declaration of p.

Now, the main thing to remember about arrays is that "the rule" about array's name decaying to a pointer to its first element applies only once. If you have an array of an array, then in value contexts, the name of the array will not decay to the type "pointer to pointer", but rather to "pointer to array". Going back to foo:

/* What should be the type of q? */
q = foo;

The name foo above is a pointer to the first element of foo, i.e., we can write the above as:

q = &foo[0];

The type of foo[0] is "array [3] of int". So we need q to be a pointer to an "array [3] of int":

int (*q)[3];

The parentheses around q are needed because [] binds more tightly than * in C, so int *q[3] declares q as an array of pointers, and we want a pointer to an array. int *(q[3]) is, from above, equivalent to int *q[3], i.e., an array of 3 pointers to int.

Hope that helps. You should also read C for smarties: arrays and pointers for a really good tutorial on this topic.

About reading declarations in general: you read them "inside-out", starting with the name of the "variable" (if there is one). You go left as much as possible unless there is a [] to the immediate right, and you always honor parentheses. cdecl should be able to help you to an extent:

$ cdecl
cdecl> declare p as  pointer to array 3 of int
int (*p)[3]
cdecl> explain int (*p)[3]
declare p as pointer to array 3 of int

To read

int (*a)[3];

      a            # "a is"
    (* )           # parentheses, so precedence changes.
                   # "a pointer to"
        [3]        # "an array [3] of"
int        ;       # "int".

For

int *a[3];

     a             # "a is"
      [3]          # "an array [3] of"
    *              # can't go right, so go left.
                   # "pointer to"
int      ;         # "int".

For

char *(*(*a[])())()

          a         # "a is"
           []       # "an array of"
         *          # "pointer to"
        (    )()    # "function taking unspecified number of parameters"
      (*        )   # "and returning a pointer to"
                 () # "function"
char *              # "returning pointer to char"

(Example from c-faq question 1.21. In practice, if you are reading such a complicated declaration, there is something seriously wrong with the code!)

53
votes

Every time you have doubts with complex declarations, you can use the cdecl tool in Unix like systems:

[/tmp]$ cdecl
Type `help' or `?' for help
cdecl> explain int (*a)[10];
declare a as pointer to array 10 of int

EDIT:

There is also a online version of this tool available here.

Thanks to Tiberiu Ana and gf

22
votes

It declares a pointer to an array of 3 ints.

The parentheses are necessary as the following declares an array of 3 pointers to int:

int* a[3];

You get better readability when using typedef:

typedef int threeInts[3];
threeInts* pointerToThreeInts;
6
votes

It means

declare a as pointer to array 3 of int

See cdecl for future reference.

4
votes

Its probably easier for the compiler to interpret than it is to you. A language defines a set of rules for what constitutes a valid expression and the compiler uses these rules to interpret such expressions (might sound complicated but compilers have been studied in length and there are a lot of standardized algorithms and tools available, you might want to read about parsing). cdecl is a tool that will translate C expressions to English. The source code is available on the website so you can check it out. The book The C++ Programming Language included sample code for writing such a program if I'm not mistaking.

As for interpreting these expressions yourself, I found the best technique to do that in the book Thinking in C++ volume 1:

To define a pointer to a function that has no arguments and no return value, you say:

void (*funcPtr)();

When you are looking at a complex definition like this, the best way to attack it is to start in the middle and work your way out. “Starting in the middle” means starting at the variable name, which is funcPtr. “Working your way out” means looking to the right for the nearest item (nothing in this case; the right parenthesis stops you short), then looking to the left (a pointer denoted by the asterisk), then looking to the right (an empty argument list indicating a function that takes no arguments), then looking to the left (void, which indicates the function has no return value). This right-left-right motion works with most declarations.

To review, “start in the middle” (“funcPtr is a ...”), go to the right (nothing there – you're stopped by the right parenthesis), go to the left and find the ‘*’ (“... pointer to a ...”), go to the right and find the empty argument list (“... function that takes no arguments ... ”), go to the left and find the void (“funcPtr is a pointer to a function that takes no arguments and returns void”).

You can download the book for free on Bruce Eckel's download site. Let's try to apply it to int (*a)[3]:

  1. Start at the name in the middle, in this case the a. So far it reads: 'a is a...'
  2. Go to the right, you encounter a closing parenthesis stopping you, so you go to the left and find the *. Now you read it: 'a is a pointer to...'
  3. Go to the right and you find [3], meaning an array of 3 elements. The expression becomes: 'a is a pointer to an array of 3...'
  4. Finally you go to the left and find the int, so finally you get 'a is a pointer to an array of 3 ints'.
2
votes

You may find this article helpful:

I've made this answer a community wiki (since it's just a link to an article, not an answer), if anyone wants to add further resources to it.

2
votes

Why what is "not int *(a[3])" exactly (referring to your last question)? The int *(a[3]) is the same as plain int *a[3]. The braces are redundant. It is an array of 3 pointers to int and you said you know what it means.

The int (*a)[3] is a pointer to an array of 3 int (i.e. a pointer to int[3] type). The braces in this case are important. You yourself provided a correct example the makes an equivalent declaration through an intermediate typedef.

The simple popular inside-out C declaration reading rule works in this case perfectly well. In the int *a[3] declaration we'd have to start from a and go right first, i.e. to get a[3], meaning that a is an array of 3 something (and so on). The () in int (*a)[3] changes that, so we can't go right and have to start from *a instead: a is a pointer to something. Continuing to decode the declaration we'll come to the conclusion that that something is an array of 3 int.

In any case, find a good tutorial on reading C declarations, of which there are quite a few available on the Net.

2
votes

In situations when you don't know what is declaration for, I found very helpful so called Right-left rule.

BTW. Once you've learned it, such declarations are peace of cake:)