Pointers Dynamic Memory Part2 (1)
Pointers Dynamic Memory Part2 (1)
Allocations
Dr. Maya B S
Assistant Professor
Department of CSE
BIT
Introduction
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);
}
9 May 2024 Dr.Maya B.S, Assistant Professor, 16
Dept.of CSE,BIT
Address of x: 3221224908
Output:
Address of y: 3221224904
Now x = 25
Output:
int x, y ;
printf (“%d %d %d”, x, y, x+y) ;
• Three-step algorithm:
1. Read in three integers x, y and z
2. Put smallest in x
• Swap x, y if necessary; then swap x, z if necessary.
3. Put second smallest in y
• Swap y, z if necessary.
#include <stdio.h>
main()
{
int x, y, z ;
………..
scanf (“%d %d %d”, &x, &y, &z) ;
if (x > y) swap (&x, &y);
if (x > z) swap (&x, &z);
if (y > z) swap (&y, &z) ;
………..
}
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
9 May 2024 Dr.Maya B.S, Assistant Professor, 61
row Dept.of CSE,BIT
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]); scanf("%d%d",&M,&N);
printf("\n"); p=allocate(M,N);
} read_data(p,M,N);
} printf("\n The array read as \n");
print_data(p,M,N);
}