Reference and Dereference operator in c

18 Aug 2022 Balmiki Mandal 0 C Programming

C Reference and Dereference Operators: Explained with Examples

In programming, the reference and dereference operators are used with pointers to manipulate memory addresses and values stored at those addresses.

Reference symbol :  & (it means holding the address)

Dereference : * (we simple called pointer)

Reference Operator (&):

The reference operator, denoted by the ampersand symbol (&), is used to obtain the memory address of a variable. It returns the address where the variable is stored in memory.

Example:

int main() {
    int num = 42;
    int* ptr = #  // Assigns the address of 'num' to the pointer 'ptr'

    printf("Address of num: %p\n", &num);
    printf("Value stored in ptr: %p\n", ptr);

    return 0;
}

In this example, the reference operator (&) is used to obtain the memory address of the variable num and assign it to the pointer ptr. The %p format specifier is used to print the memory addresses.

Dereference Operator ():

The dereference operator, denoted by the asterisk symbol (), is used to access the value stored at a memory address pointed to by a pointer. It retrieves the value stored at the specified memory address.

Example:

int main() {
    int num = 42;
    int* ptr = #  // Assigns the address of 'num' to the pointer 'ptr'

    printf("Value of num: %d\n", num);
    printf("Value pointed to by ptr: %d\n", *ptr);

    return 0;
}

In this example, the dereference operator (*) is used to access the value stored at the memory address pointed to by the pointer ptr. It retrieves the value of the variable num indirectly through the pointer.

It's important to note that the dereference operator should be used only with valid pointers that have been initialized with a valid memory address. Dereferencing an uninitialized or NULL pointer can lead to undefined behavior or crashes.

Top Resources

Arithmetic operator in c

Assignment operator in c programming

Relational operator in c programming

Logical Operator in c programming

Bitwise operator in c programming

sizeof operator in c programming

Understanding the Comma Operator in C Programming

Dot Operator in c programming

Using && Logical AND Operator in C Programming

Further Reading:

 For further information and examples, Please visit[ C-Programming From Scratch to Advanced 2023-2024]

 

Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.