In this blog let’s try to understand about pointer. So, what is pointer?... pointer is thing that
used to point something in a group. For example,
Here, the pointer is
used to point the temperature in the gauge.
Similarly, in computer the data gets stored in memory and
each data is assigned with an address in the memory. So, the pointer is used to
point the data, in other words pointer contains a memory address of that
particular data. (int a = 10; here the ‘a’ indirectly act as a pointer which
has the value ‘10’.) Now we can see that how arrays are similar with pointer.
We know that array is a continuous block of memory that stores multiple data of
same kind. Let’s have a close look
In c program pointer a declared with ’*’ symbol followed by a variable (eg : int
*ptr).
int a[10];---------------------------( 1 )------------------>
this array stores 10 integers at max, here all elements in array is referenced
with the variable ‘a’. which is more less equal to pointer. So by using pointer
concepts we can create a dynamic array.
Int *p=( int * ) malloc ( x*sizeof(int));-----------------(
2 )-----------> here the x is the count of elements that user provides
during runtime. (int *) is used instead of (int) because return type is a
pointer variable. Malloc is a dynamic memory allocation that allocates required
size of bytes and return the pointer that points at first position.
(x*sizeof(int)) is used define memory space required ‘x’ is user defined value
and ‘sizeof()’ is function that returns the size of a datatype of variable that
passed as its parameter, here ‘int’ is passed. If user’s x value is 10 then its creates 10 blocks of
memory each with the size of int. So, from above explanation we understood that
both (1) and (2) are more or less same.
Now you can ask that Java does not support “pointers”. Yes
of course JAVA does not support pointers at user level but at inside its JVM
pointers are used. So it is worthy to know about it.
In two dimensional array , int a[10][5]-------------(3)------------->
here, ‘10’ independent blocks each of size ‘5’ gets created and first
value(here, 10) act as a index value. Here double pointers are used, the
pointer which contains address of another pointer is called as double pointer.
Its is represented as ** symbol followed by variable, (eg **a). Now let’s look
at how the two-dimensional array is stored in memory.
Here,
the “A” act as a double pointers which points to the address block of pointers
A[1],….,A[10] which pointes to the block that contains actual data, thus arrays
are similar to pointers.
I hope you could get some idea about pointers...any queries comment below and do subscribe for more blog's
Follow me @ facebook
Comments
Post a Comment