I\'m trying to deepen my understanding on syntax relevant to pointer in C, and I noticed that If I created an array of int first, int(*)[]
is a way of giving a poin
Both b
and c
point to the same memory but the difference is big:
int
and pointer to an array of 3 int
s)b
is dereferenced to a single integer pointed by b
while c
is dereferenced to an array of 3 int
s which means you can assign an integer to *b
(*b = 10;
) but you can't do the same for c
(but only with specified index (*c)[0] = 10
)b + 1
will increase the value of b
by sizeof(int)
while c + 1
will increase the value of c
by 3*sizeof(int)
If they're different, when should I use one way instead of choosing the other one?
As any other type in C, it should be used based on your needs and application. Most commonly used is the int *b;
option since it gives you more flexibility. With such pointer you can handle array of any size, it is more commonly used and more readable. While pointer to an array binds you to an array of pre-defined size, its syntax is less readable (in my opinion) and thus will be harder to review/debug the code. In my experience I've never seen a production code which uses pointer to an array but this doesn't mean you cannot use it if you find any advantage of it in your application.