Reputation: 983
What is the difference between
int * a[10];
and
int (*b)[10];
I know that the first one is an array of pointers to integers, but what is the second one? If I try assigning
int (*c)[10] = a;
what am I actually doing to c?
Upvotes: 5
Views: 2419
Reputation: 27
int *a[10] is an array of pointers, i.e. a pointer array which can hold 10 different integer memory allocations (spaces), viz
a[0] = (int *)calloc(10, sizeof(int));
a[1] = (int *)calloc(50, sizeof(int));
and so on.. and generally the sizeof a will be (10 * 4) => 40.
int (*b)[10] is a pointer to array that points to an array of integer i.e. b points to integer array of size 10, viz,
b = &(integer array[10]);
the above can be used as in the given example:
int c[10];
int (*b)[10];
b = &c;
The advantage of using the pointer to array is that, the array can be changed from time to time during the course of execution according to the need of the code.
Upvotes: 2
Reputation: 2838
You should be doing this:
int d[10];
int (*c)[10] = d;
For more:
C pointer to array/array of pointers disambiguation
Upvotes: 1
Reputation: 31642
I once learned a fancy trick (maybe that's not the right word) about reading c declarations that really stuck with me: http://www.antlr.org/wiki/display/CS652/How+To+Read+C+Declarations
Start at the variable name (or innermost construct if no identifier is present. Look right without jumping over a right parenthesis; say what you see. Look left again without jumping over a parenthesis; say what you see. Jump out a level of parentheses if any. Look right; say what you see. Look left; say what you see. Continue in this manner until you say the variable type or return type.
Using that mental algorithm, you can easily read and understand any C variable declaration.
Sometimes, when they get really complicated, it's nice to use this little utility: cdecl which is available as a stand-alone app, but also as a website: http://cdecl.org/
Upvotes: 5
Reputation: 263307
See if you can install the cdecl
command for your system. (On Ubuntu, sudo apt-get install cdecl
.) There's also a web interface at cdecl.org.
Here's what it told me for your examples on my system:
$ cdecl
Type `help' or `?' for help
cdecl> explain int * a[10];
declare a as array 10 of pointer to int
cdecl> explain int (*b)[10];
declare b as pointer to array 10 of int
cdecl>
Upvotes: 10
Reputation: 210525
Second one is a pointer to an array of 10 integers. Where? God knows; you never initialized it.
If you assign a
to it, you're making it point to the same array of 10 integers that a
pointed to... nothing fancy.
Upvotes: 5