In C programming, the address and indirection operators are used with pointers to manipulate memory locations.
The address operator &
returns the memory address of a variable. It can be used to obtain the memory address of a variable that is already defined, and to pass a variable by reference to a function.
For example, suppose we have a variable named x
that stores an integer value. We can obtain its memory address using the address operator as follows:
int x = 10;
int *ptr = &x; // obtain the memory address of x
In this code, the variable ptr
is a pointer to an integer, and we use the address operator to assign the memory address of x
to ptr
.
The indirection operator *
is used to access the value of a variable that is stored at a memory location pointed to by a pointer. It is also called the "dereference" operator.
For example, suppose we have a pointer named ptr
that points to an integer value. We can access the value stored at the memory location pointed to by ptr
using the indirection operator as follows:
int x = 10;
int *ptr = &x; // obtain the memory address of x
int y = *ptr; // access the value stored at the memory location pointed to by ptr
In this code, the variable y
is assigned the value stored at the memory location pointed to by ptr
using the indirection operator.
We can also use the indirection operator to modify the value of a variable pointed to by a pointer:
int x = 10;
int *ptr = &x; // obtain the memory address of x
*ptr = 20; // modify the value stored at the memory location pointed to by ptr
In this code, the value stored at the memory location pointed to by ptr
is modified to 20
using the indirection operator.
Together, the address and indirection operators allow us to manipulate memory locations using pointers, which is a powerful feature of the C programming language.
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.