Pointers
Pointers
Pointers
Module-1
Table of Content
⮚ Introduction
⮚ Basic Concept
⮚ Pointer Declarations
⮚ Pointer Expressions
⮚ Null Pointer
Aim
b. Applications of Pointers
cases
Introduction
Variable Value
Address p = &xyz;
50
1380
p 1380
1
50
p xyz
Accessing the Address of a Variable
&(a+b)
• Pointing at expression.
Example
#include <stdio.h>
int main()
{
int a;
float b, c;
double d;
char ch;
a = 10;
b = 2.5;
c = 12.36;
d = 12345.66;
ch = 'A';
printf("%d is stored in location %u \n\n", a, &a);
printf("%f is stored in location %u \n\n", b, &b);
printf("%f is stored in location %u \n\n", c, &c);
printf("%lf is stored in location %u \n\n", d, &d);
printf("%c is stored in location %u\n", ch, &ch);
return 0;
}
OUTPUT:
• Example:
int *count;
float *speed;
p = &xyz;
• Pointer variables must always point to a data item of the same type.
float x;
int *p;
int a, b;
int *p;
p = &a;
b = *p; Equivalent to b=a
Example 1
#include <stdio.h>
void main()
{
int a, b;
int c = 5; Equivalent
int *p;
a = 4 * (c + 5);
p = &c;
b = 4 * (*p + 5); Output:
printf("a=%d b=%d \n", a, b);
}
Example 2
#include <stdio.h>
void main()
{
int x, y;
int *ptr;
x = 10;
ptr = &x; // 'ptr' stores the address of 'x'
y = *ptr; // 'y' gets the value stored at the address 'ptr' is pointing to (which is 'x')
printf("%d is stored in location %u \n", x, &x); // Prints value of 'x' and its address
printf("%d is stored in location %u \n", *&x, &x); // Prints value of 'x' and its address (using *&x, which is x)
printf("%d is stored in location %u \n", *ptr, ptr); // Prints value pointed by 'ptr' and the address stored in 'ptr'
printf("%d is stored in location %u \n", y, &y); // Prints value of 'y' and its address
printf("%u is stored in location %u \n", ptr, &ptr); // Prints address stored in 'ptr' and address of 'ptr' itself
printf("%d is stored in location %u \n", y, &y); // Prints value of 'y' and its address again
*ptr = 25; // Modifies the value of 'x' through the pointer 'ptr'
printf("\nNow x = %d \n", x); // Prints the new value of 'x'
}
Output:
Pointer Expressions
#include <stdio.h>
void swap(int x, int y);
int main()
{
int a, b;
a = 5;
b = 20;
swap(a, b); a and b do not swap
printf(“\n a = % d, b = % d”, a, b);
return 0;
}
Output
void swap(int x, int y)
{ a = 5, b = 20
int t;
t = x; x and y swap
x = y;
y = t;
}
Example: passing arguments by reference
#include <stdio.h> {
void swap(int *x, int *y); int temp;
int main() temp = *x;
{ *x = *y;
int a, b; *y = temp;
printf("\n Enter the value of a= printf("\n Values of a and b after
"); swaping=%d and %d", *x, *y);
scanf("%d", &a); }
printf("\n Enter the value of b=");
scanf("%d", &b);
printf("\n Values of a and b before
swaping=%d and %d", a, b);
swap(&a, &b); OUTPUT:
return 0;
}
void swap(int *x, int *y)
Pointers and Arrays
#include <stdio.h>
int main()
{
int *ptr = NULL; // Null
Pointer
printf("The value of ptr is
%p", ptr);
return 0;
}
Summary
Outcomes: