Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

c - Is int *array[32] a pointer to an array of 32 ints, or an array of 32 pointers to int? Does it matter?

If I write

int *columns[32];

am I defining an array with 32 pointers to ints?
Or is it a pointer to an array of 32 ints?

How do I differentiate between the two? Is there a difference?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Expanding on a comment to another answer:

There's a fairly straightforward procedure for reading C declarations. Start with the leftmost identifier in the declarator and work your way out, remembering that [] and () bind before *. Given the declaration

int *columns[32];

break it down as

     columns                  -- columns
     columns[32]              -- is a 32-element array
    *columns[32]              -- of pointers
int *columns[32]              -- to int.  

If the declaration had been

int (*columns)[32];

then it would break down as

      columns                 -- columns
    (*columns)                -- is a pointer
    (*columns)[32]            -- to a 32-element array
int (*columns)[32]            -- of int.  

This will also help you build up complex declarations. Suppose you wanted to declare an array of pointers to functions returning pointers to arrays of char:

          f                     -- f
          f[N]                  -- is an N-element array
         *f[N]                  -- of pointers
        (*f[N])()               -- to functions
       *(*f[N])()               -- returning pointers
      (*(*f[N])())[M]           -- to M-element arrays
     *(*(*f[N])())[M]           -- of pointers
char *(*(*f[N])())[M];          -- to char

cdecl is a nice tool, but after you'd done this exercise a few times, you shouldn't need it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...