Pointers
Pointers
CSE 109
● Example :
○ type *var_name;
○ Here type/base type specified the type of the object the
pointer can point to
○ Such as: int *p; here p is a pointer to an integer
Introduction to Pointers
Pointer Operators
● & : returns the address of the variable it precedes
● * : returns the value stored at the address it precedes
int *p, q;
q = 199;
p = &q;
printf("%d", *p);
Introduction to Pointers : Indirection
int *p, q;
p = &q;
*p = 199; Indirection
printf("%d", q);
printf(“%p”, p);
Introduction to Pointers
int q;
double *fp; Problem?
fp = &q;
*fp = 100.23;
Introduction to Pointers
int q;
double *fp; Problem?
fp = &q; Overwrites the adjacent additional
*fp = 100.23; 6 bytes to q
Introduction to Pointers
int *p;
*p = 10; Unassigned pointer,
program will crash
Example
int *p;
double q, temp;
temp = 1234.34;
p = &temp;
q = *p;
printf("%f", q);
Pointer Operators
int *p;
p = 200 (address)
p++;
p = 204 (address)
Pointer Operators
int *p;
P points to the 200th integer
p = p + 200; past the one to which
previously pointed
Pointer Operators
● Multidimensional array
● float balance[10][5] → how to access balance[3][1] using pointer?
Pointer with Arrays
● Multidimensional array
● float balance[10][5] → how to access balance[3][1] using pointer?
float *p;
p = (float *) balance; p = balance might
not work in all
*(p + (3 * 5) + 1) compilers as p
might point to the
first row and p+1
will point to the
second row
Pointer with Arrays : Indexing
p = str;
● int* arr[3]
○ arr is an array of 3 pointers to integers.
○ Each element of arr is a pointer that can point to an integer.
○ It's often used when you need an array where each element is a
pointer, and each pointer can point to a different memory location.
● int (*arr)[3]
○ arr is a pointer that can point to the beginning of an array of 3
integers.
○ It's often used to represent a 2D array, and pointer arithmetic can be
used to navigate through rows and columns.
Pointer to an array example
int a[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
int (*p)[3]; // Declare a pointer to an array of 3 integers
int* fun()
{
static int A = 10;
return (&A);
}
int main()
{
int* p;
p = fun();
printf("%p\n", p);
printf("%d\n", *p);
return 0;
}
Return pointer from a function
int* fun()
{
If we used ‘int A’ (local
static int A = 10;
return (&A); variable) inside the
} function, it would have
gone outside scope
once the function exits
int main()
→ Segmentation fault
{
int* p;
p = fun();
printf("%p\n", p);
printf("%d\n", *p);
return 0;
}
Pointer to Pointer
Pointer to
Pointer Variable
pointer
p = &ch;
mp = &p;
**mp = 'A';
Resources for study
● https://www.tutorialspoint.com/cprogramming/c_pointers
.htm
● https://www.scaler.com/topics/c/array-of-pointers-in-c/