0% found this document useful (0 votes)
8 views40 pages

7 Pointers

Uploaded by

yoyoshyam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views40 pages

7 Pointers

Uploaded by

yoyoshyam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Slide 1

Pointers
Slide 2

Recall

 How do you create a pointer pointing to the variable i declared


below?
 char i=„A‟;
 How can you access the value of p through pointer?
 What will be printed if you access i through an integer pointer?
Slide 3

Array and Pointer

 Pointer variable can be assigned to array’s base address and using


the pointer increment and decrement operator all the array elements
can be accessed.
 The ++ operator is used to jump one location forward from the
current pointer location.
 Similarly -- operator can be used to jump one location behind.
 The jump distance depends on the pointer type.
Slide 4

Multiple Pointer Declaration

 If you declare multiple pointers on the same line, you must precede
each of them with an asterisk:
/* one pointer, one regular int */
int *pointer1, nonpointer1;
/* two pointers */
int *pointer1, *pointer2;
Slide 5

1-D array and pointers


int a[]={1,2,3,4};
Assuming the int to be 4 bytes
a[0],0[a],*a,*(a+0) 1
a: base array address 1000
1000 a
a+2: base array address+2 *a 1
1000+2*4 bytes 1004 a +1
1000+8=1008 *(a +1) 2
1008 a +2
*(a +2) 3
int *b;
1012 a +3
b=a; *(a +3) 4
b: base array address of array
a1000
*b: value at 1000 1 1000 b
*(b+1): value at 10022 2002
Slide 6

Activity
main(){
int a[]={1,2,3,4};
1. Fill in the blanks with
int i;
two statements such
f(a);
that all the elements in
for(i=0;i<4;i++)
the array gets
printf("%d ",a[i]);}
incremented by one.
f(int *p){
int i;
2. Now convert the 2
for(i=0;i<4;i++){
statements into one.
______;
______;
}
}
6

1. (*p)++ : This will increment the value.


p++ : Jump 4 bytes to next element location
2. (*p++)++;
Slide 7

Lab Exercises

 Write a function that copies elements of one array into another from a
specific position till the length specified. The function prototype should
look like
void arrayCopy(int *a, int position, int length)
(15 mins)

 Write a function that reads a command line argument and prints the
length of the command line arguments excluding the program name.

(15 mins)

7
Slide 8

Array of arrays

int a1[2]={5,6};
int a2[2]={7,8};
a1
int *a[2];//Array of pointers 2000
5 **a
a[0]=a1; 2004
a[1]=a2; 6
a 1000
2008 a2
2000 **(a+1)
a+1 1004 7
2008 2012
8
a[0]*a
a[1]*(a+1)

*a+1
How will you get to 2004?
a[0][1],*(a[0]+1),*(*(a+0)+1) ???
8
Slide 9

2-D array and pointer

 int a[2][2]={{5,6},{7,8}};
can be viewed as array of arrays where a[0] is base address of row 1,
a[1] is the base address of row 2 etc.

Base address
a,*a,a[0]
5 **a,a[0][0]
*a+1,a[0]+1 *(*a+1),a[0][1]
6
a+1,*(a+1),a[1] 7 **(a+1),a[1][0]
8
a[0][1]*(a[0]+1)*(*(a+0)+1) 6
a[1][1]*(a[1]+1)*(*(a+1)+1) 8
9
Slide 10

Pointer Operators

 *: value at the address specified by the variable


 &: address of the variable
 ++: increments the pointer by size of the variable
 --:decrements the pointer by size of the variable
 +: addition of a pointer variable and a constant value
 -: subtraction of pointer and a constant value and subtraction of two
pointers.
 ==: comparison of pointers

10
Slide 11

Test your understanding

Predict the output of the program below:

int main(){
int a[2][2]={{5,10},{15,20}};

printf("%d\n",**a+1);
printf("%d\n",*(*a+1));
printf("%d\n",*(*(a+1)));
return 0;
}

11

Answer :
6
10
55
Slide 12

Array of pointers

 Array of pointers to int:


ptrs
int *ptrs[2];
int i=10,j=11; 2001

2001 10 i
ptrs[0]=&i;
ptrs[1]=&j;
2002

2002 11 j

*(ptrs[1]), ptrs[1][0]11

12
Slide 13

Pointer to a pointer

 A pointer variable that points to another pointer variable is a pointer


to a pointer represented by **.

int i=10
int *j; 2004 1003
int **k; 2004 1003 10
j=&i; k j i
k=&j;
k is a pointer to a pointer to an int

**k10

13
Slide 14

String and Pointer

 Both the print statements prints


main(){
Shankara.
char s[]="Shankara";
char *p="Shankara";  ‘s’ is an array of characters

 ‘p’ is a pointer to the first character


printf("%s",s); where Shankara is stored.

printf("%s",p);  Note that the printf() statement


with %s prints the string char by

} char without having to increment


the array index or pointer position.

14
Slide 15

Tell me why

 Why char *p="Shankara"; is correct while


int *i=10; gives compilation error

 The reason behind this is that p contains the address of the string
constant which is stored in the string table.
 You can see this by compiling the code with –S option  gcc
filename.c –S.
 Open filename.s and locate Shankara.
 This is a feature of assembly language. “Shankara” is an example of
static data. The string will always be the same, and more importantly,
we know exactly how long it is. Therefore, it may be stored in memory
directly, and does not need to be computed at runtime.

15
Slide 16

Activity
int main(){
char c[4]="abcde";
printf("%s",c);
}
 Execute the above code and find out what happens if the size is
specified as
 4
 5
 6
 7
 Can you change the value of the string variable c as shown below?
 c=“pqrst";

16

Answer:

Size = 4  abcd<Garbage Value>


Size = 5  abcd<Garbage Value>
Size = 6  abcde
Size = 7  abcde

If we re-assign the different value for c:


c=“pqrst";

No problem in compilation but on execution following error is received:


error: incompatible types in assignment
Slide 17

Array of Strings

 Array of strings can be represented in two ways:


 char str[4][5]or
char str[][5]={"John","Mary","Sita","Rama"};
 char *str[];(array of pointers to string)
 First way is preferred to read the string from the console.
 Second way is the more preferred way to manipulate and print!

17
Slide 18

Test your understanding

What will the code print?


Is there any problem with this code. How can you resolve this?
main(){
char n1[][4]={"John","Mary","Sita","Rama"};
int i;
for(i=0;i<4;i++)
printf("%s ",n1[i]);
}

18

Make the string size 5 instead of 4.


Slide 19

Activity

Type and execute the code listed below. Do you see any problem?
main(){
char *names[4];
int i;
for(i=0;i<4;i++){
printf("enter the name \n");
scanf("%s",names[i]);}
for(i=0;i<4;i++){
printf("%s \n",names[i]);
}
}
19
Slide 20

Solution

 The problem with the previous program is that the space was not
allocated for the strings.
 One way to solve this is by statically allocating space for the strings.
 Other way is through dynamic memory allocation (which is coming up)

main(){
char names[6][4];
char *nm[4];
int i;
for(i=0;i<4;i++){
printf("enter the name \n");

20
Slide 21

scanf("%s",names[i]);
nm[i]=names[i];
}
for(i=0;i<4;i++){
printf("%s ",nm[i]);}
}

21
Slide 22

Pointers to functions

 Like variables, functions also have addresses.


 A pointer variable can point to an address of a function too.
 The next example maintains a function pointer that points to a
particular function based on user’s input and then later executes that
function through the function pointer.

22
Slide 23

main(){
int i;
int f();
Prototype declaration
int g();
int (*fptr)(); Function pointer
printf("type 0 for f() or 1 for g() ");
scanf("%d", &i);
if(i)
fptr=g;
Assigning function address to function pointer
else
fptr=f;
(*fptr)(); Calling function through function pointer
return 0;
}
23
Slide 24

int f(){
printf("f() called");
return 0;
}
int g(){
printf("g() called");
return 0;
}

Output:
type 0 for f() or 1 for g() 1 You type this
g() called

24
Slide 25

Activity

 int *x;  is a pointer to an int


 int (*x)[]
 int *x[]
 int (*(*x)[])
 int (*x[])(void)
 int (*(*x)[])(void)
 int (*(*(*x)[])(void))

What will happen if you omit the parentheses around *x[] in last
statement?

25

int *x;  x is a pointer to an int


int (*x)[]  x is a pointer to array of int
int *x[] x is an array of pointer to int
int (*(*x)[]) x is pointer to array of pointer to int
int (*x[])(void) x is array of pointer to function (void) returning int
int (*(*x)[])(void) x is pointer to array of pointer to function (void) returning int
int (*(*(*x)[])(void)) x is pointer to array of pointer to function (void) returning pointer to
int
int (**(*x)[](void))  x is pointer to array of function (void) returning pointer to pointer to int
Slide 26

Lab Exercise

 Create 2 sort functions one that sorts in ascending order and other
that sorts in descending order and other. Based on the user input
call the appropriate sort function at runtime.
(20 mins)

26
Slide 27

Dynamic memory allocation

 Using arrays we can reserve a fixed memory location.


 Let us suppose that there can be a maximum of 100 employees in a
department and minimum of 2. In such cases, allocation of 100
locations for a department having 2 employee would be sheer waste of
space.
 In such cases, we can use dynamic memory allocation that allows us to
allocate memory as and when we need, instead of allocating and
reserving it before hand.
 The memory allocated at the runtime of the program (when execution is
in progress) is known as dynamic memory allocation.

27

Let us say we n number of students can enroll for a tutorial and the value of n is unknown to the
programmer because he has no idea t how many students are going to enroll for the tutorial. Maximum
number of enrollments could go upto 100. So, to make program work and to be on safer side,
programmer allocates the memory for 100 students.

And when program is in execution, actual number of students enrolled were 20 only. That means, out of
memory allocated for 100 students only 20 are being used and rest of the 80 memory locations are
wasted as system will not provide it for allocation (as it is already reserved by the programmer)

To solve this issue, a programmer can use dynamic memory allocation to allocate memory for only 20
students at runtime.
Slide 28

Memory related functions in <stdlib.h>


 Memory allocation:
 void* malloc(size_t n ): returns a chunk of memory. We need
to cast it to the type we want and assign it to a pointer variable.
 void* calloc(size_t no_of_data, size_t
size_of_each_data): returns a chunk of memory. We need to
cast it to the type we want and assign it to a pointer variable.
 Initializes the allocated memory to 0.
 Reallocating the memory
 void * realloc(void * p, size_t n) : changes the size of
previously allocated memory
 Releasing the memory
 free(void * p): frees up the memory allocated with malloc(),
calloc() or realloc()
28

If the memory allocation fails (because of unavailability of memory), a null pointer is returned.

If the new size of the memory block is not available in the old location realloc() function allocates a new
memory block in a new location and the content of the memory block is also copied to the new location.
Slide 29

Generic pointer

 malloc() and calloc() returns a generic pointer called void *.


 This type of pointer can be used to point to any type of memory.
 Hence, one pointer variable can be used to point to different types of
data.
 Therefore, it is important that we typecast the void pointer into the
type that we desire, so that we can use pointer arithmetic effectively to
iterate over the chuck of data.

29
Slide 30

calloc/malloc using Generic pointer

Example below demonstrate the usage of calloc/malloc with generic pointer:

main(){
int *empno, n,i;
printf("enter the number of employees: ");
scanf("%d",&n);

empno=(int *) malloc(n*sizeof(int));
or (int *) calloc(n,sizeof(int));
Check if memory is actually
if(empno=='\0'){ allocated as per the request
printf("memory not available"); or not.
exit(0);}
else
for(i=0;i<n;i++){
printf("\nenter the employee number: ");
scanf("%d",(empno+i));
}
30
Slide 31

printf("printing all the employee numbers");


for(i=0;i<n;i++)
printf("\nemployee number %d : %d\n", i, *(empno+i));
free(empno);}
Output:
enter the number of employees: 3
enter the employee number: 5432
You enter this
enter the employee number: 6453
enter the employee number: 7654
printing all the employee numbers
employee number 0 : 5432
employee number 1 : 6453
employee number 2 : 7654

31
Slide 32

Heap

 Variables created dynamically through malloc() or calloc()


are created in memory space called heap.
 Heap is also called free memory, free store, free pool or dynamic
memory.
 Every program has this pool of memory space available. How much
of memory is available is determined by the runtime system.

32
Slide 33

Lab Exercises

 Write a program that accepts names of any number of participants who


are willing to enroll for a game. Pass the names to a function that will
sort it in ascending order.
(30 mins)

 Write a program that takes an input string from command line, creates
a new string by coping an existing string and converting it into upper
case. Display both the input string and the new string with upper case.
Don’t use any library function.
(20 mins)

33
Slide 34

Runtime Memory Layout

 Code segment
 Place where the code is stored.
 Data segment/ Static memory
 Shared address space where the global variables are stored
 Remains throughout the program
 Stack/ Automatic/Temporary memory
 Memory that is automatically created and destroyed
 Each function gets its own block of memory
 After the function returns stack automatically unwinds
 Heap/Free store
 Memory where dynamically allocated elements are kept
 Grows throughout the life of the of the program as and when required.

34
Slide 35

Test your understanding

 What will happen on compilation/execution of the following code?


main(){
int *i=10;
printf("%d \n",i);
}}

 Which of the following is correct?


1. char *p=“a”;
2. *p=„a‟;
3. *p=“a”;

35
Slide 36

const

 const declaration implies that the value cannot be changed.


 The const has to be initialized in the same line of its declaration
before it is used. (unless it is declared as extern)
 Example: const int num=4;
 const can be declared locally (also as function argument)
 This keyword has been borrowed from C++.

36
Slide 37

Pointers and const arrays

const char str[10]="abc";


str[0]=„m‟;
 incorrect – newer compilers gives illegal assignment error
while some of the older give warning
const char str[10]="abc";
char *p=str;
*p='m';
 incorrect – newer compilers gives while some of the older
give warning
 cannot convert from const char[10] to char *

37
Slide 38

const Pointer & Pointer to a const


 A constant pointer always point to the same memory location
 Array name is by default is a const pointer
 They must be initialized when declared
 Example: char * const ptr=&p;
 Note that constant pointer is different from pointer to a constant.
 char const * ptr=&p;
 Pointer to a constant implies the value the pointer is pointing to
cannot be changed.
 But the variable (memory location) that the pointer points to can be
changed.

38
Slide 39

int main(){
int k=10;
int l=20;
int *const p=&k;
const int *q=&k;
*p=*p+5; or int const *q=&k;
printf("%d\n",*p);
//*q=*q+5;
change the value of k through pointers
printf("%d\n",*q);

//p=&l; Error!
printf("%d\n",*p);
q=&l; change the address of the pointers
printf("%d\n",*q);
return 0;}
What is this?
const int *const r;
39
Slide 40

Activity

 Assume the following array declared in main


int a[3]={31,24,35};
 Which of the following function is appropriate to change the elements
of an array to 1,2,3
int change1(const int*c)
int change( int*const c)
 Which of the above function can be used to change the array itself
int a[10]={31,24,35};
c=a;

40

int change( int*const c)


None, because array name is by default is a const pointer

You might also like