Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between int bar[10] vs int (*bar)[10]

int bar[10]; /* bar is array 10 of int, which means bar is a pointer to array 10 of int */

int (*bar)[10]; /* bar is a pointer to array 10 of int */

According to me they both are same, am I wrong? Please tell me.

Edit: int *bar[10] is completely different.

Thanks Raja

like image 291
Raja Avatar asked Dec 13 '22 09:12

Raja


2 Answers

They are completely different. The first one is an array. The second one is a pointer to an array.

The comment you have after the first bar declaration is absolutely incorrect. The first bar is an array of 10 ints. Period. It is not a pointer (i.e. your "which means" part makes no sense at all).

It can be expressed this way:

typedef int T[10];

Your first bar has type T, while you r second bar has type T *. You understand the difference between T and T *, do you?

like image 119
AnT Avatar answered Dec 27 '22 19:12

AnT


You can do this:

int a[10];

int (*bar)[10] = &a;  // bar now holds the address of a

(*bar)[0] = 5;  // Set the first element of a

But you can't do this:

int a[10];

int bar[10] = a;  // Compiler error!  Can't assign one array to another
like image 30
Oliver Charlesworth Avatar answered Dec 27 '22 17:12

Oliver Charlesworth