Professional Documents
Culture Documents
10 Pointers
10 Pointers
- Compiler will allocate a memory location for Quantity and places the
value in that location. Suppose the address of that location is 5000, then
• Once a pointer variable has been declared, it can be made to point to a variable
using an assignment statement :
int *p = &Quantity ;
Such variables that hold memory
addresses are called
Pointer Variables.
Now…
v = 3; //assigns 3 to v
return 0;
}
05/23/2024 CSE 1001 Department of CSE 13
Example - Accessing via pointers.
#include <stdio.h>
int main()
{
int var1, var2; //two integer variables
int *ptr; //pointer to integers
ptr = &var1; //set pointer to address of
*ptr = 37; //same as var1=37
( Dereferencing)
var2 = *ptr; //same as var2=var1
printf(“%d”, var2); //verify var2 is 37
return 0;
}
05/23/2024 CSE 1001 Department of CSE 14
Reference and dereference
operators
& is the ‘reference’ operator and can be read as
"address of"
int main()
return 0;
if (p1==p2)
printf(“p1 and p2 points to same location”);
if (p1!=p2)
printf(“p1 and p2 NOT pointing to same location”);
return 0;
05/23/2024 } CSE 1001 Department of CSE 29
Array accessing using Pointers - Example
// array accessed with pointer
#include <stdio.h>
int main()
{
return 0;
}
Element in 2d represented as
*(*(a+i)+j)
or
*(*(p+i)+j)
p=a;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf(“%d \t“, *(*(p+i)+j));
printf("\n“);
}
return 0;
05/23/2024 CSE 1001 Department of CSE 36
}
Array of pointers
We can use pointers to handle a table of strings.
char name[3][25];
name is a table containing 3 names, each with a
maximum length of 25 characters (including ‘\0’)
OUTPUT:
Integer variable is = 7
Float variable is = 7.600000