l7 Pointers
l7 Pointers
xyz variable
50 value
1380 address
int arr[20];
:
&arr;
• Pointing at array name.
&(a+b)
• Pointing at expression.
#include <stdio.h>
main()
{
int a;
float b, c;
double d;
char ch;
• Example:
int *count;
float *speed;
• Once a pointer variable has been declared, it
can be made to point to a variable using an
assignment statement like:
int *p, xyz;
:
p = &xyz;
– This is called pointer initialization.
#include <stdio.h>
main()
{
int a, b;
int c = 5; Equivalent
int *p;
a = 4 * (c + 5) ;
p = &c;
b = 4 * (*p + 5) ;
printf (“a=%d b=%d \n”, a, b) ;
}
x = 10 ;
ptr=&x;
ptr = &x ; &x&*ptr
y = *ptr ;
printf (“%d is stored in location %u \n”, x, &x) ;
printf (“%d is stored in location %u \n”, *&x, &x) ;
printf (“%d is stored in location %u \n”, *ptr, ptr) ;
printf (“%d is stored in location %u \n”, y, &*ptr) ;
printf (“%u is stored in location %u \n”, ptr, &ptr) ;
printf (“%d is stored in location %u \n”, y, &y) ;
*ptr = 25;
printf (“\nNow x = %d \n”, x);
}
January 18, 2024 16
Output: Address of x: 3221224908
Address of y: 3221224904
Now x = 25
Output:
}
}
}
January 18, 2024 26
Pointers and Arrays
x &x[0] 2500 ;
• malloc
– Allocates requested number of bytes and returns a
pointer to the first byte of the allocated space.
• calloc
– Allocates space for an array of elements, initializes
them to zero and then returns a pointer to the
memory.
• free
Frees previously allocated space.
• realloc
– Modifies the size of previously allocated space.
• Examples
p = (int *) malloc (100 * sizeof (int)) ;
• A memory space equivalent to “100 times the size of an
int” bytes is reserved.
• The address of the first byte of the allocated memory is
assigned to the pointer p of type int.
p
• Example:
int **p;
p=(int **) malloc(3 * sizeof(int *));
p[0]
p int ** int *
p[1] int *
int *
p[2]
Elements accessed
p=(int **) calloc(h, sizeof (int *) );
like 2-D array elements.
for(i=0;i<h;i++)
p[i]=(int *) calloc(w,sizeof (int));
return(p);
} Allocate array of
integers for each
January 18, 2024 58
row
2-D Array: Contd.
void print_data(int **p,int h,int w) main()
{ {
int i,j; int **p;
for(i=0;i<h;i++) int M,N;
{
for(j=0;j<w;j++) printf("Give M and N \n");
printf("%5d ",p[i][j]);Give M and N scanf("%d%d",&M,&N);
printf("\n"); 33 p=allocate(M,N);
} 123 read_data(p,M,N);
} 456 printf("\n The array read as \n");
789 print_data(p,M,N);
}
The array read
as
January 18, 2024 1 2 3 59
4 5 6