C ProgrammingPointers – Level-II
Prepared by Mohammed SikanderTechnical LeadCranes Software International Limited
char *ptr_name = “SIKANDER”;char str_name[ ] = “SIKANDER”;
• Can we make a pointer point to string literal?
char *ptr_name = “SIKANDER”;char str_name[ ] = “SIKANDER”;
printf(“ %s \n“ , ptr_name);printf(“ %s \n“ , str_name);
• Can we print the string through pointer.
char *ptr_name = “SIKANDER”;char str_name[ ] = “SIKANDER”;
printf(“Length of %s = %d\n“ , ptr_name , strlen(ptr_name));
printf(“Length of %s = %d\n“ , str_name , strlen(str_name));
char *ptr_name = “SIKANDER”;char str_name[ ] = “MUQADDAR”;
printf(“Size of ptr_name = %d\n“ , sizeof(ptr_name));
printf(“Size of str_name = %d\n“ , sizeof(str_name));
Array of PointersWe can have arrays where each element can be a pointer
int *
char **
int *
int *
int *
int *
int *arr_ptr[5];
int
int
int
int
int
int arr[5];
What is size of arr?What is size of arr_ptr?
Array of Pointers
char **
Char *arr_ptr[5];
char *
char *
char *
char *
char *
char
char
char
char
char
Char arr[5];
What is size of arr?What is size of arr_ptr?
int x = 10;int *ptr =
&x;
int arr[5] int *ptr =
arr;
int a = 10;int b = 23;int arr[ ] = {12,34,54};int *ptr[ ] = {&a , &b ,
arr};
Array of Pointers
char *capitalCities[] = { “Bangalore”,“Chennai”, “Guwahati”, “Amravathi”};
Bangalore
Chennai
Guwahati
Amravathi
****
char *
char *
char *
char *
char *str = “VxWorks”;
Array of Pointers
names++ tries to change the base address of array. We cannot change the base address of array. Str was a pointer, names is an array.
Array of Pointers
char **
*Bangalor
eChennai
Guwahati
Amravathi NULL
****
char *
char *
char *
char *
void pointers
Void pointers can hold the address of any type of object.
Dereferencing on void pointers are not allowed.
Incrementing void pointers are not allowed.
Program to understand realloc.If realloc allocates new block in different location, it copies data from old block to new block
By making ptr as constant pointer, any modification to ptr can be caught at compile time.