DEV Community

Cover image for C - Even more pointers, arrays and strings
Haile Melaku
Haile Melaku

Posted on

C - Even more pointers, arrays and strings

Wait we haven't finished pointers yet, if you haven't seen the previous blog post i highly suggest you check it out.
So on this blog post we are going to dive deep into even more pointers.


#C – Pointer to Pointer

Pointer to pointer is a form of chained pointer in which a pointer holds the address of another pointer.

The declaration of pointer to pointer is done by adding an additional asterisk in front of its name.

A pointer with an n amount of asterisk() can hold the address of any pointer with a n - 1 asterisks().

TYPE **VAR_NAME;

In this case the pointer with a double asterisk() can hold the address of a pointer with a single asterisk() and they have the same value across.

Example

Image description
Output

Image description

To Generalize this Example:
num == *ptr1 == **ptr2
&num == ptr1 == *ptr2
&ptr1 == ptr2

When declaration of variable the memory layout for this example is:
Image description

Image description

Image description

After assigning the value 10 to num the memory layout will look like

Image description

Image description

Image description

After adding in the address of the num to ptr1 and ptr1 to ptr2 the memory layout will look like this:

Image description

Image description

Image description

As you can see in the above tables we used numbers to represent the address of variables to better understand the concept, address are most commonly put in the like the output of the example in some form of hexadecimal.

In the table the value of num = 10 and address = 13, the ptr1 holds the address of num as a value which is 13 and the address of ptr1 is 17.

Now we come to pointer to pointer in the table ptr2 holds the address of the other pointer ptr1 as a value and this is the case of ptr2(double pointer) it holds the address of other pointer in it.


#Two dimensional (2D) arrays

A two dimensional arrays is also know as array of arrays.

To declare a two dimensional array

TYPE ARRAY_NAME[x][Y]

Where type can be any valid C data type, arrayName will be a valid C identifier, x number of rows and y number of columns.

To initializing two-dimensional arrays we use two method

int a[3][4] = {{0, 1, 2, 3},{6, 3, 61, 7},{10, 75, 1, 16}};
Enter fullscreen mode Exit fullscreen mode
int a[3][4] = {0,1,2,3,6,3,61,7,10,75,1,16};
Enter fullscreen mode Exit fullscreen mode

with 2D array, you must always specify the second dimension even if you are specifying elements during the declaration.

int a[][] = {1, 2, 3 ,4 }
Enter fullscreen mode Exit fullscreen mode

This is invalid because the second value is not specified.

Example

Image description

Output
Image description

The memory layout to the following example is

Image description

Image description

Top comments (0)