L8- Pointers in C.ppt
L8- Pointers in C.ppt
Module-8: Pointers in C
Content for the slides have been taken from the various sources and
from the reference books.
• x ='*ptr++;
• This allocates 10 contiguous bytes of memory space and the address of first
byte is stored in the pointer variable ptr.
• This space can hold 5 integers. The allocated memory contains garbage value.
• ptr = (int *) malloc (5 * sizeof (int));
• This allocates the memory space to hold five integer values.
malloc()
• If there is not sufficient memory available in heap then malloc() returns NULL.
So we should always check the value returned by malloc().
• ptr = (float *) malloc(1O*sizeof(float) );
• if ( ptr == NULL )
• printf("Sufficient memory not available");
• Unlike memory allocated for variables and arrays, -dynamically allocated
memory has no name associated with it.
• So it can be accessed only through pointers. We have a pointer which points to
the first byte of the allocated memory and we can access the subsequent bytes
using pointer arithmetic.
malloc()
calloc()
realloc()
realloc()
free()
Dynamic Arrays
• The memory allocated by malloc(), calloc() and realloc() is always
made up of contiguous bytes.
• Moreover in C there is an equivalence between pointer notation
and subscript notation i.e. we can apply subscripts to a pointer
variable.
• So we can access the dynamically allocated memory through
subscript notation also.
• We can utilize these features to 'create dynamic arrays whose size
can vary during run time.
Dynamic Arrays
Pointers To Functions
• The code of a function resides in memory hence every function has an address like all
other variables in the program.
• We can get the address of function by just writing the function's name without ().
Declaring A Pointer To A Function
• We have seen that functions have addresses, so we can have pointers that can
contain these addresses and hence point to them.
• The syntax for declaration of a pointer to a function is as
• return type (*ptr_name)(type1, type2, ……);
• For example
• float (*fp)( int );
• char (*func_p)(float, char);
• Here fp is a pointer that can point to any function that returns a float value
and accepts an int value argument.
• Similarly func_p is a pointer that can point to functions returning char and
accepting float d char as arguments
Thank you for your attention!
< Questions?