Memory Address
When a variable is created in C, a memory address is assigned to the variable.
The memory address is the location of where the variable is stored on the
computer.
When we assign a value to the variable, it is stored in this memory address.
To access it, use the reference operator (&), and the result represents where the
variable is stored:
Example
#include <stdio.h>
int main() {
int myAge = 43;
printf("%p", &myAge);
return 0;
Output-0x7ffe5367e044
Note: The memory address is in hexadecimal form (0x..). You will probably not
get the same result in your program, as this depends on where the variable is
stored on your computer.
Pointers
Creating Pointers
You learned from the previous chapter, that we can get the memory
address of a variable with the reference operator &:
Example
int myAge = 43; // an int variable
printf("%d", myAge); // Outputs the value of myAge (43)
printf("%p", &myAge); // Outputs the memory address of myAge
(0x7ffe5367e044)
A pointer is a variable that stores the memory address of another variable
as its value.
A pointer variable points to a data type (like int) of the same type, and is
created with the * operator.
The address of the variable you are working with is assigned to the pointer:
Example
#include <stdio.h>
int main() {
int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the
name ptr, that stores the address of myAge
// Output the value of myAge (43)
printf("%d\n", myAge);
// Output the memory address of myAge
(0x7ffe5367e044)
printf("%p\n", &myAge);
// Output the memory address of myAge with the
pointer (0x7ffe5367e044)
printf("%p\n", ptr);
return 0;
}
Example explained
Create a pointer variable with the name ptr, that points to an int variable
(myAge). Note that the type of the pointer has to match the type of the variable
you're working with (int in our example).
Use the & operator to store the memory address of the myAge variable, and
assign it to the pointer.
Now, ptr holds the value of myAge's memory address.
Question-1
Write a program in C to add two numbers using pointers.
Visual Presentation:
Solution-
#include <stdio.h>
int main() {
int fno, sno, *ptr, *qtr, sum; // Declare integer variables fno, sno, sum, and integer pointers ptr, qtr
printf("\n\n Pointer : Add two numbers :\n");
printf("--------------------------------\n");
printf(" Input the first number : ");
scanf("%d", &fno); // Read the first number from the user
printf(" Input the second number : ");
scanf("%d", &sno); // Read the second number from the user
ptr = &fno; // Assign the address of fno to the pointer ptr
qtr = &sno; // Assign the address of sno to the pointer qtr
sum = *ptr + *qtr;
printf(" The sum of the entered numbers is : %d\n\n", sum); // Print the sum of the entered numbers
return 0;
}