Pointers are one of the most difficult concepts in C language to grasp. Many programmers get confused in pointers.I am one of them. I decided to write series of blog posts covering basic to advance concepts of pointers.
This is the first part to understand very basic of pointer that what pointer actually is and how we can store/access data through pointers.
Put simply
Accessing value of a variable that is pointed to by a pointer
In our above code if we wish to access value of x using ptrToX. We can do so like this
1) *ptrToX gives you 3
2) ptrToX (without *) gives you the memory address of x or we can say value of ptrToX (which is the memory of address of x)
We can perform any operation on x using ptrToX through * operator. Here are some examples
For example if we write ptrToX++ will increment the value of ptrToX instead of what it points to (in our case x). That means it will change the memory address pointed to by ptrToX and ptrToX will not more point to x but to some other memory address.
This is the first part to understand very basic of pointer that what pointer actually is and how we can store/access data through pointers.
Put simply
A pointer is a variable that contains the address of a variableLets try to understand pointers using some code.
int x=3;In above code we simply took a variable x of type int. Then we define a pointer (* denotes that variable is a pointer and it is known as indirection or dereferencing operator) ptrToX of type int and assigned address of x to ptrToX. Now ptrToX points to x. Note that ptrToX do not contain value of x (i.e 3) instead it contains memory address of x. Now we can access and manipulate value of x using ptrToX.
int *ptrToX;
ptrToX=&x;
Accessing value of a variable that is pointed to by a pointer
In our above code if we wish to access value of x using ptrToX. We can do so like this
int y=*ptrToX;now y contains 3 (value of x). As you can see we can access the value of variable that is pointed to by a pointer using * operator.
1) *ptrToX gives you 3
2) ptrToX (without *) gives you the memory address of x or we can say value of ptrToX (which is the memory of address of x)
We can perform any operation on x using ptrToX through * operator. Here are some examples
y=*ptrToX+1; (add 1 to x and save in y)
*ptrToX*=1; (multiply value of x by 1 and store in x)Important note:
For example if we write ptrToX++ will increment the value of ptrToX instead of what it points to (in our case x). That means it will change the memory address pointed to by ptrToX and ptrToX will not more point to x but to some other memory address.
Comments
Post a Comment
Share your wisdom