CPPS Unit 3 Pointers
CPPS Unit 3 Pointers
#include <stdio.h>
int main() {
int x = 10; // Normal integer variable
int *ptr; // Pointer to integer
return 0;
}
Important Points
1."A pointer is a derived data type that can
store the address of other variables or a
memory location."
✅ This means a pointer doesn't store data
directly, but rather stores the memory address
of another variable.
Example:
int x = 5;
int *ptr = &x; // ptr stores the address of x
2."Pointers allow us to access and modify the
data stored at a specific memory location.“
int main() {
int *ptr_int;
char *ptr_char;
float *ptr_float;
double *ptr_double;
return 0;
}
🧾 Real-Life Example: Contact Book
•.
• Pointer Declaration
• Pointer Initialization
• Pointer Dereferencing
1. Pointer Declaration
Syntax:
datatype *pointer_name;
Example:
int *ptr;
p1 = &a; 0x1010
0x1014 0x1004 p1
p2 = &b; 0x1018 0x1008 p2
0x101C
MCQ,S
Difference Between Variables And Pointer
Access Just use the Use *ptr to access the value at the
value variable name (x) address
• The compiler will allocate space for the string “HELLO”, and copy
the starting address of this space into the variable ‘s1’.
Variable s1
Address 0x120
Contents 0x100
Example
#include <stdio.h>
int main() {
// String constant using pointer
char *str = "Hello, World!";
return 0;
}
String using pointers in C
#include <stdio.h>
int main() {
// Declare a string constant using a pointer
// char *str = "Pointer Loop";
char str[6] = "Hello"; // string variable
char *ptr = str;
printf("\n");
return 0;
}
Pointers and Arrays
• Pointers are also used to access arrays.
Ex:
int myNumbers[4] = {25, 50, 75, 100} ;
Output:
0x7ffe70f9d8f0
0x7ffe70f9d8f0
• myNumbers is a pointer to the first element in myNumbers,
use the * operator to access the value of the first element.
Output:
13 17
Alternate way to use pointer to access array
elements
int arr[10]; /* Declare array ‘arr’ of 10 integers */
int *pa; /* Declare ‘pa’ to be a pointer to a integer */
int b;
b = pa[i]; /* The pointer variable can be used like the array
name */
Note: pa[i] is same as *(pa+i)
Accessing the elements of the two dimensional array
via a simple pointer
p2 = arr1[0];
/* Giving only one dimension of ‘arr’ evaluates to the address of the first
row of array ‘arr’ */
printf("arr1[0][0]=%d\n",p2[0][0]);
printf("arr1[2][3]=%d\n",p2[2][3]);
Another way to declare 2D pointers
int arr1[3][5] = {{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15}};
int (*p2)[3][5];
p2 = arr1; /* Or, p2 = &arr1[0][0] */
printf("arr1[0][0]=%d\n",(*p2)[0][0]);
printf("arr1[2][3]=%d\n",(*p2)[2][3]);
printf("arr1[1][4]=%d\n",(*p2)[1][4]);
Pointer Arithmetic in C