Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Explain reference and pointer in C programming?
In C programming, pointers are variables that store memory addresses of other variables. C does not have references like C++ − it only has pointers for indirect access to variables.
Syntax
datatype *pointer_name; pointer_name = &variable_name;
Pointers in C
Pointers store the memory address of another variable
They can hold NULL values
They enable pass by reference functionality
They can be declared without initialization
Use
*operator to access the value at the address (dereference)Use
&operator to get the address of a variable
Example: Basic Pointer Operations
This example demonstrates pointer declaration, initialization, and dereferencing −
#include <stdio.h>
int main() {
int a = 2, b = 4;
int *p;
printf("Address of a = %p<br>", (void*)&a);
printf("Address of b = %p<br>", (void*)&b);
p = &a; /* p points to variable a */
printf("Value of a = %d<br>", a);
printf("Value at *p = %d<br>", *p);
printf("Address in p = %p<br>", (void*)p);
p = &b; /* p now points to variable b */
printf("Value of b = %d<br>", b);
printf("Value at *p = %d<br>", *p);
printf("Address in p = %p<br>", (void*)p);
return 0;
}
Address of a = 0x7fff5fbff73c Address of b = 0x7fff5fbff738 Value of a = 2 Value at *p = 2 Address in p = 0x7fff5fbff73c Value of b = 4 Value at *p = 4 Address in p = 0x7fff5fbff738
Pass by Reference Using Pointers
C achieves pass by reference functionality using pointers −
#include <stdio.h>
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a = 10, b = 20;
printf("Before swap: a = %d, b = %d<br>", a, b);
swap(&a, &b);
printf("After swap: a = %d, b = %d<br>", a, b);
return 0;
}
Before swap: a = 10, b = 20 After swap: a = 20, b = 10
Key Points
- C has no references − only pointers for indirect access
-
Pointer declaration:
int *ptr; -
Address operator:
&variablegets the address -
Dereference operator:
*pointergets the value
Conclusion
Pointers are fundamental in C for dynamic memory allocation, function parameters, and efficient data manipulation. Unlike C++, C uses only pointers for indirect variable access.
