In a normal c/c++ program we write main function as either
int main(int c, char **argv)
or
int main(int c, char *argv[])
Here argv represents an array of pointers but we even represent double pointer(pointer to pointer) using **.
ex:
char p,*q,**r;
q=&p;
r=&q;
Here r is a double pointer and not array of pointers.
Can any one explain the difference?
Here is a list of the differences present between Pointer to an Array and Array of Pointers. A user creates a pointer for storing the address of any given array. A user creates an array of pointers that basically acts as an array of multiple pointer variables. It is alternatively known as an array pointer.
So, when we define a pointer to a pointer. The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double-pointers.
An array is treated as a pointer that points to the first element of the array. 2D array is NOT equivalent to a double pointer! 2D array is "equivalent" to a "pointer to row".
A pointer is used to store the address of variables. So, when we define a pointer to pointer, the first pointer is used to store the address of the second pointer. Thus it is known as double pointers.
When used as a function parameter
char a[] // compiler interpret it as pointer to char
is equivalent to
char *a
and similarly, in main
's signature, char *argv[]
is equivalent to char **argv
. Note that in both of the cases char *argv[]
and char **argv
, argv
is of type char **
(not an array of pointers!).
The same is not true for the declaration
char **r;
char *a[10];
In this case, r
is of type pointer to pointer to char
while a
is of type array of pointers to char
.
The assignment
r = a; // equivalent to r = &a[0] => r = &*(a + 0) => r = a
is valid because in this expression again array type a
will be converted to pointer to its first element and hence of the type char **
.
Always remember that arrays and pointers are two different types. The pointers and arrays equivalence means pointer arithmetic and array indexing are equivalent.
Suggested reading:
char a[]
was identical to char *a
. If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With