Pointer Array

When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of the array. Base address i.e address of the first element of the array is also allocated by the compiler.
int arr[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two bytes, the five elements will be stored as follows:

Here variable arr will give the base address, which is a constant pointer pointing to the first element of the array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In short, arr has two purpose - it is the name of the array and it acts as a pointer pointing towards the first element in the array.
arr is equal to &arr[0] by default
We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.
Now we can access every element of the array arr using p++ to move from one element to another.
NOTE: You cannot decrement a pointer once incremented. p-- won't work.

Pointer to Array :-

we can use a pointer to point to an array, and then we can use that pointer to access the array elements.

#include <stdio.h> int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
return 0;
}
In the above program, the pointer *p will print all the values stored in the array one by one.


Pointer and Character strings :-

Pointer can also be used to create strings. Pointer variables of char type are treated as string.
char *str = "Hello";
The above code creates a string and stores its address in the pointer variable str. The pointer str now points to the first character of the string "Hello". Another important thing to note here is that the string created using char pointer can be assigned a value at runtime.
char *str;
str = "hello"; //this is Legal
The content of the string can be printed using printf() and puts().
printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string. Therefore we do not need to use indirection operator *.

Array of Pointers :-

We can also have array of pointers. Pointers are very helpful in handling character array with rows of varying length.

char *name[3] = {
"Adam",
"chris",
"Deniel"
};
//Now lets see same array without using pointer
char name[3][20] = {
"Adam",
"chris",
"Deniel"
};

In the second approach memory wastage is more, hence it is prefered to use pointer in such cases. When we say memory wastage, it doesn't means that the strings will start occupying less space, no, characters will take the same space, but when we define array of characters, a contiguos memory space is located equal to the maximum size of the array, which is a wastage, which can be avoided if we use pointers instead.






Previous Next

Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here


Ittutorial