Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

C Programming Pointers Slides, Slides of C programming

Very Good and Detailed C Programming Pointers Notes

Typology: Slides

2017/2018

Uploaded on 05/16/2018

abhishek-rana-4
abhishek-rana-4 🇮🇳

5

(1)

3 documents

1 / 18

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
© Oxford University Press 2012. All rights reserved.
CHAPTER 13
POINTERS
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12

Partial preview of the text

Download C Programming Pointers Slides and more Slides C programming in PDF only on Docsity!

CHAPTER 13

POINTERS

© Oxford University Press 2012. All rights reserved.

UNDERSTANDING THE COMPUTER’S MEMORY

  • (^) Every computer has a primary memory. All our data and programs need to be placed in the primary memory for execution.
  • (^) The primary memory or RAM (Random Access Memory which is a part of the primary memory) is a collection of memory locations (often known as cells) and each location has a specific address. Each memory location is capable of storing 1 byte of data
  • (^) Generally, the computer has three areas of memory each of which is used for a specific task. These areas of memory include- stack, heap and global memory.
  • (^) Stack- A fixed size of stack is allocated by the system and is filled as needed from the bottom to the top, one element at a time. These elements can be removed from the top to the bottom by removing one element at a time. That is, the last element added to the stack is removed first.
  • (^) Heap- Heap is a contiguous block of memory that is available for use by the program when need arise. A fixed size heap is allocated by the system and is used by the system in a random fashion.
  • (^) When the program requests a block of memory, the dynamic allocation technique carves out a block from the heap and assigns it to the program.
  • (^) When the program has finished using that block, it returns that memory block to the heap and the location of the memory locations in that block is added to the free list.

INTRODUCTION

  • (^) Every variable in C has a name and a value associated with it. When a variable is declared, a specific block of memory within the computer is allocated to hold the value of that variable. The size of the allocated block depends on the type of the data. int x = 10;
  • (^) When this statement executes, the compiler sets aside 2 bytes of memory to hold the value 10. It also sets up a symbol table in which it adds the symbol x and the relative address in memory where those 2 bytes were set aside.
  • (^) Thus, every variable in C has a value and an also a memory location (commonly known as address) associated with it. Some texts use the term rvalue and lvalue for the value and the address of the variable respectively.
  • The rvalue appears on the right side of the assignment statement and cannot be used on the left side of the assignment statement. Therefore, writing 10 = k; is illegal.

DECLARING POINTER VARIABLES

  • (^) Actually pointers are nothing but memory addresses.
  • (^) A pointer is a variable that contains the memory location of another variable.
  • (^) The general syntax of declaring pointer variable is data_type *ptr_name; Here, data_type is the data type of the value that the pointer will point to. For example: int *pnum; char *pch; float *pfnum; int x= 10; int ptr = &x; The '' informs the compiler that ptr is a pointer variable and the int specifies that it will store the address of an integer variable. The & operator retrieves the lvalue (address) of x, and copies that to the contents of the pointer ptr.

POINTER EXPRESSIONS AND POINTER ARITHMETIC

  • (^) Pointer variables can also be used in expressions. For ex, int num1=2, num2= 3, sum=0, mul=0, div=1; **int ptr1, ptr2; ptr1 = &num1, ptr2 = &num2; **sum = ptr1 + ptr2; *mul = sum * ptr1; *ptr2 +=1; div = 9 + ptr1/ptr2 - 30;
  • (^) We can add integers to or subtract integers from pointers as well as to subtract one pointer from the other.
  • (^) We can compare pointers by using relational operators in the expressions. For example p1 > p , p1==p2 and p1!=p2 are all valid in C. When using pointers, unary increment (++) and decrement (--) operators have greater precedence than the dereference operator (*). Therefore, the expression *ptr++ is equivalent to (ptr++). So the expression will increase the value of ptr so that it now points to the next element. In order to increment the value of the variable whose address is stored in ptr, write (ptr)++

NULL POINTERS

A null pointer which is a special pointer value that is known not to point anywhere. This means that a NULL pointer does not point to any valid memory address. To declare a null pointer you may use the predefined constant NULL, int *ptr = NULL; You can always check whether a given pointer variable stores address of some variable or contains a null by writing, if ( ptr == NULL) { Statement block; } Null pointers are used in situations if one of the pointers in the program points somewhere some of the time but not all of the time. In such situations it is always better to set it to a null pointer when it doesn't point anywhere valid, and to test to see if it's a null pointer before using it.

© Oxford University Press 2012. All rights reserved.

PASSING ARGUMENTS TO FUNCTION USING POINTERS

The calling function sends the addresses of the variables and the called function must declare those incoming arguments as pointers. In order to modify the variables sent by the caller, the called function must dereference the pointers that were passed to it. Thus, passing pointers to a function avoid the overhead of copying data from one function to another. **#include<stdio.h> int main() { int num1, num2, total; printf(“\n Enter two numbers : “); scanf(“%d %d”, &num1, &num2); sum(&num1, &num2, &total); printf(“\n Total = %d”, total); getch(); return 0; } void sum ( int *a, int *b, int *t) { *t = a + b; }

POINTERS AND ARRAYS

int arr[5] = {1, 2, 3, 4, 5}; int *ptr = &arr[0]; ptr++; printf(“\n The value of the second element of the array is %d”, *ptr); Write a program to read and display an array of n integers #include<stdio.h> int main() { int i, n; int arr[10], *parr; parr = arr; printf(“\n Enter the number of elements : “); scanf(“%d”, &n); for(i=0; i <n; i++) scanf(“%d”, (parr+i)); for(i=0; i <n; i++) printf(“\n arr[%d] = %d”, i, *(parr+i)); }

POINTERS AND STRINGS

  • (^) Now, consider the following program that prints a text.
  • #include<stdio.h>
  • (^) main()
  • (^) { char str[] = “Oxford”; *char pstr = str;
  • printf(“\n The string is : “);
  • (^) *while( pstr != ‘\0’)
  • (^) *{ printf(“%c’, pstr);
  • pstr++;
  • (^) }
  • (^) }
  • (^) In this program we declare a character pointer *pstr to show the string on the screen. We then "point" the pointer pstr at str. Then we print each character of the string in the while loop. Instead of using the while loop, we could have straight away used the function puts(), like puts(pstr);
  • Consider here that the function prototype for puts() is:
  • (^) int puts(const char *s); Here the "const" modifier is used to assure the user that the function will not modify the contents pointed to by the source pointer. Note that the address of the string is passed to the function as an argument.

POINTERS AND STRINGS CONTD.

  • (^) Consider another program which reads a string and then scans each character to count the number of upper and lower case characters entered
  • (^) #include<stdio.h>
  • (^) int main()
  • *{ char str[100], pstr;
  • (^) int upper = 0, lower = 0;
  • printf(“\n Enter the string : “);
  • (^) gets(str);
  • pstr = str;
  • (^) *while( pstr != ‘\0’)
  • { if(pstr >= ‘A’ && pstr <= ‘Z’)
  • (^) upper++;
  • else if(pstr >= ‘a’ && pstr <= ‘z’)
  • (^) lower++;
  • (^) pstr++;
  • (^) }
  • (^) printf(“\n Total number of upper case characters = %d”, upper);
  • (^) printf(“\n Total number of lower case characters = %d”, lower);
  • (^) }

© Oxford University Press 2012. All rights reserved.

POINTER TO FUNCTION

  • This is a useful technique for passing a function as an argument to another function.
  • (^) In order to declare a pointer to a function we have to declare it like the prototype of the function except that the name of the function is enclosed between parentheses () and an asterisk () is inserted before the name. / pointer to function returning int / int (func)(int a, float b);
  • (^) If we have declared a pointer to the function, then that pointer can be assigned to the address of the right sort of function just by using its name.
  • (^) When a pointer to a function is declared, it can be called using one of two forms: (func)(1,2); ORfunc(1,2); #include <stdio.h> void print(int n); main() { void (fp)(int); fp = print; (fp)(10);* fp(20); return 0; } void print(int value) { printf("\n %d", value); } Comparing Function Pointers if(fp >0) // check if initialized { if(fp == print) printf("\n Pointer points to Print"); else printf("\n Pointer not initialized!"); }

© Oxford University Press 2012. All rights reserved.

PASSING A FUNCTION POINTER AS AN ARGUMENT TO A

FUNCTION

A function pointer can be passed as a function's calling argument. This is done when you want to pass a pointer to a callback function. include <stdio.h> int add(int, int); int subt(int, int); int operate(int (operate_fp) (int, int), int, int); main() { int result; result = operate(add, 9, 7); printf ("\n Addition Result = %d", result); result = operate(sub, 9, 7); printf ("\n Subtraction Result = %d", result); } int add (int a, int b) { return (a+b);} nt subtract (int a, int b){ return (a-b);} int operate(int (operate_fp) (int, int), int a, int b) { int result; result = (operate_fp) (a,b); return result; }*