Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between double pointer and array of pointers

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?

like image 470
Rakesh kumar Avatar asked Nov 03 '15 05:11

Rakesh kumar


People also ask

What is the difference between array of pointers and pointer to the array?

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.

What is the difference between pointer and double 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.

Is a double pointer an array?

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".

What is a double pointer?

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.


1 Answers

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:

  • But I heard that char a[] was identical to char *a.
  • Why are array and pointer declarations interchangeable as function formal parameters?
like image 167
haccks Avatar answered Sep 28 '22 03:09

haccks