Pointers verses Variables

Slides:



Advertisements
Similar presentations
Pointers in C Rohit Khokher
Advertisements

ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
More Pointers Write a program that: –Calls a function to input an integer value –The above function calls another function that will double the input value.
Introduction to C Programming CE Lecture 18 Dynamic Memory Allocation and Ragged Arrays.
Introduction to C Programming CE
What does this program do ? #include int main(int argc, char* argv[]) { int i; printf("%d arguments\n", argc); for(i = 0; i < argc; i++) printf(" %d: %s\n",
ARRAYS In this Lecture, we will try to develop understanding of some of the relatively complex concepts. The following are explained in this lecture with.
POINTERS. 1.a) POINTER EXPRESSIONS Pointer variables can be used in expression If p1 and p2 are properly declared and initialized pointers then following.
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
1 Homework HW4 due today HW5 is on-line Starting K&R Chapter 5 –Skipping sections for now –Not covering section 5.12.
ECE Application Programming
Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP Spring 2014 C Part IV.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CCSA 221 Programming in C CHAPTER 7 WORKING WITH ARRAYS 1.
Arrays, Strings, and Memory. Command Line Arguments #include int main(int argc, char *argv[]) { int i; printf("Arg# Contents\n"); for (i = 0; i < argc;
POINTERS IN C Pointer Basics, Pointer Arithmetic, Pointer to arrays and Pointer in functions.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Pointers and Arrays Subject: T0016 – ALGORITHM AND PROGRAMMING Year: 2013.
Arrays in C. What is Array? The variables we have used so far can store a single value. Array is a new type of variable capable of storing many values.
Pointers to pointers & multi-dimensional arrays
Memory allocation & parameter passing
Stack and Heap Memory Stack resident variables include:
Computer Organization and Design Pointers, Arrays and Strings in C
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
UNIT 5 C Pointers.
Functions and Pointers
Day 03 Introduction to C.
Lecture 7 Arrays 1. Concept of arrays Array and pointers
Hassan Khosravi / Geoffrey Tien
Lecture-5 Arrays.
Day 03 Introduction to C.
INC 161 , CPE 100 Computer Programming
Hassan Khosravi / Geoffrey Tien
Module 2 Arrays and strings – example programs.
Arrays in C.
Programming Languages and Paradigms
Lecture 6 C++ Programming
Dynamic memory allocation and Intraprogram Communication
Functions and Pointers
14th September IIT Kanpur
C Passing arrays to a Function
Dynamic memory allocation and Intraprogram Communication
Chapter 5 POINTERs.
Programming and Data Structures
Chapter 15 Pointers, Dynamic Data, and Reference Types
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
CS111 Computer Programming
Programming with Pointers
EECE.2160 ECE Application Programming
prepared by Senem Kumova Metin modified by İlker Korkmaz
Outline Defining and using Pointers Operations on pointers
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Homework Starting K&R Chapter 5 Good tutorial on pointers
Pointers and Arrays Beyond Chapter 16
7. Pointers, Dynamic Memory
C (and C++) Pointers April 4, 2019.
C Programming Lecture-8 Pointers and Memory Management
Exercise Arrays.
Chapter 9: Pointers and String
Chapter 9: Pointers and String
Arrays and Pointers (part 2)
Presentation transcript:

Pointers & Dynamic Memory Allocations in C CHAPTER 3

Pointers verses Variables Pointers are variables that contains memory addresses. A variable contains a specific value. A pointer contains the address of a variable that contains a specific value. Like other variables, pointer must be declared before they can be used.

Pointer Declaration Just like variables, each pointer has a name and a data type that can be at the pointed address. e.g.: int *ptr ; // A pointer declaration int cnt=32 ; // A variable declaration … ptr = &cnt ; Note that, pointer names have an indicator ( * ) character, that is differentiating them from variable names. At the previous example, ptr is declared as a pointer, which pointing a memory address contains an integer value.

Pointer Declaration Pointers are indirectly referencing variables. cnt is directly references a variable whose value is 32. 32 cnt ptr is indirectly references a variable whose value is 32. 32 ptr cnt

Operators Used with Pointers & : The “address of ” operator is used mostly just before any variable name for indicating its memory address. * : The content of operator is used before a variable name, for indicating the specific value existing at the address pointer contains. Note that, & operator is used with variables, and * operator is used with pointers.

Operators Used with Pointers e.g.: int x=1, y=2; int *ip; ip = &x; // The address of x is assigned to ip y = *ip; // The content of the address ip has // is copied to the variable y. (y=x) printf(“x=%d y=%d”, x, y); The output will be: x=1 y=1

Operators Used with Pointers e.g.: int x=1; int *ip; ip = &x; *ip = *ip + 10; /* The value 10 is added to the content of the address ip has */ printf(“x=%d *ip=%d”, x, *ip); The output will be: x=11 *ip=11

Operators Used with Pointers e.g.: *ip +=1; is same as ++ *ip; and *ip ++; All of them above increments the value of the address in ip by 1. *(ip++); is indicating the value of the NEXT address, which ip has. *(ip++) ¹ *ip++

Operators Used with Pointers e.g.: #include <stdio.h> void main() { int u=3, v, *pu, *pv; pu = &u; v = *pu; pv = &v; printf(“\n u=%d, *pu = %d”, u, *pu); printf(“\n v=%d, *pv = %d”, v, *pv); } The output will be: u=3, *pu=3 v=3, *pv=3

Operators Used with Pointers e.g.: #include <stdio.h> void main() { int u1, u2, v=3, *pv; u1 = 2 * ( v + 5); pv = &v; u2 = 2 * ( *pv + 5); printf(“\n u1 = %d, u2 = %d”, u1, u2); } The output will be: u1= 16, u2 = 16

Operators Used with Pointers e.g.: #include <stdio.h> void main() { int u=1, v=2, *pv; printf(“\n u = %d, v = %d”, u, v); pv = &u; *pv = 6; pv = &v; *pv = 0; } The output will be: u= 1, v = 2 u= 6, v = 2 u= 6, v = 0

Pointers and Arrays When an array is declared, the followings are done automatically: The array size of spaces are allocated within the memory. A pointer as the array name is declared. The address of the first location is assigned to the pointer( so, it points the initial array element). So, the followings are exactly same: myarray = &myarray[0] myarray+1 = &myarray[1] myarray + 9 = &myarray[9]

Pointers and Arrays e.g.: pv = list; *(pv+3) = 12; int list[5]=“1, 3, 5, 7, 9}, *pv; pv = list; *(pv+3) = 12; 1 2 3 4 5 List pv 1 2 3 12 5 List pv

Pointers and Arrays e.g.: #include <stdio.h> void main() { int i, list[5]={5,10,15,20,25}, *pv; pv=list; for (i=0; i< 5; i++) *(pv + i)= *(pv+i) + 2; for (i=0; i< 5; i++) printf(“%d ,”,list[i]); } Output will be: 7, 12, 17, 22, 27

Pointers and Arrays e.g.: #include <stdio.h> void main() { int i =0; char line[81], *pv; gets(line); while (*(line+i) !=‘\0’) { printf(“%c”,*(line+i)); i++; } } // End of program This program reads a line at most 80 character and then displays it character by character.

Pointers and Arrays e.g.: Read elements of an array and find the sum of array elements with using pointers. #include <stdio.h> void main() { int i =0, arr[5], *parr, sum = 0; for(i=0; i<5; i++) { printf(“\n Enter the value of location %d”,i+1); scanf(“%d”, &arr[i]); } parr = arr; sum += *(parr+i) printf(“\n The sum is found %d”,sum); } // End of program

Pointers and Function Arguments When a variable is used as an argument on a function call, the value of this variable is being passed into the function if variable is not globally declared, its content can not be altered in the function). When a pointer is used as an argument on a function call, the address in the pointer is being passed into the function. So, just like globally declared variables, in the function, the content of a local variable, that its address is passed into the function, can be altered.

Pointers and Function Arguments #include <stdio.h> void funct1(int, int); void funct2(int *, int *); void main() { int u = 1, v = 3; printf(“\n Before calling func1, u=%d , v=%d”,u,v); func1(u, v); printf(“\n After calling funct1, u=%d , v=%d”,u,v); funct2(&u, &v); printf(“\n After calling funct2, u=%d , v=%d”,u,v); } void funct1( int u, int v) { // The Output will be u= 0; v=0; // Before Calling func1 u = 1, v = 3 } // After Calling funct1 u = 1, v = 3 // After Calling funct2 u = 0, v= 0 void funct2( int *pu, int *pv) { *pu= 0; *pv=0;

Examples e.g.: /* Read a character string and display it in reverse order*/ #include <stdio.h> void main() { char line[81], *pline ; printf(“\n Enter a string of characters :”); gets(line); for (pline=line; *pline !=‘\0’, pline++); // Goes to the last character. pline - -; // Comes back to the last character for (; pline > line; pline - -) // Display characters from last to 2th printf(“%c ”,*pline!=line, pline - - ); printf(“%c ”,*pline!=line, pline - - ); // Display the last character }

Examples e.g.: /* Count the number of characters of a string */ #include <stdio.h> void main() { int cnt = 0; char line[81], *pline ; printf(“\n Enter a string of characters :”); gets(line); for (pline = line; *pline !=‘\0’, pline++) { ++cnt; ++ pline; // Come back to the last character } printf(“\n There are %d characters”,cnt);

Examples e.g.: /* Count the occurrence of a character within a string */ #include <stdio.h> void main() { int cnt = 0; char line[81], ch, *pline ; printf(“\n Enter a string of characters :”); gets(line); printf(“\n Enter the target character :”); scanf(“%c”, &ch); for (pline = line; *pline !=‘\0’, pline++) if (*pline == ch) ++cnt; printf(“\n There are %d occurrence ”,cnt); }

Examples e.g.: /* Reads a character string and counts the existing words */ #include <stdio.h> void main() { char line[81], *pline ; int cword =0; printf(“\n Enter a string of characters :”); gets(line); for (pline=line; *pline ==‘ ’, pline++); // Skips blanks. while (pline !=‘\0’) { cword ++; for ( ; ((pline !=‘\0’) and ( *pline!=‘ ‘); pline++) ; // skips letters for ( ; ((pline !=‘\0’) and ( *pline==‘ ‘); pline++) ; // skips blanks } printf(“There are %d words in the string.”,cword);

Examples e.g.: /* Read a character string and display one word each line */ #include <stdio.h> void main() { char line[81], *pline ; printf(“\n Enter a string of characters :”); gets(line); for (pline=line; *pline ==‘ ’, pline++); // Skips blanks. while (pline !=‘\0’) { printf(“\n”); for ( ; ((pline !=‘\0’) and ( *pline!=‘ ‘); pline++) printf(“%c”,*pline) ; // display letters for ( ; ((pline !=‘\0’) and ( *pline==‘ ‘); pline++) ; // skips blanks }

Dynamic Memory Allocation The process of allocating and de-allocating memory while the program is in execution is called Dynamic Memory Allocation. Specially, on a situation which the memory requirement is not possible to be estimated on program design time, the required memory has to be allocated dynamically on run time. Also, when the allocated memory is not going to be used, on run time, it may be de-allocated (free).

Dynamic Memory Allocation On memory allocation, a pointer is required to keep the reference address of the allocated memory. The memory allocation functions are declared within the library <alloc.h>. malloc(); is the function for allocating a number of bytes within the memory. It returns the reference address of the allocated memory part. free(); is the function for de-allocating a memory part that was allocated dynamically. The reference address of the memory part has to be given as argument to free().

Dynamic Memory Allocation Consider the following code; they are almost same: e.g.: void main() { int list[10]; … } { int list; list = (int *) malloc(10 * sizeof(int)); free(list);

Array of Pointers It is an array that all its elements are pointers. Elements of an array of pointer may points some other arrays, which can be think as a multidimensional array. Really, when a multidimensional array is declared: A pointer is declared with the name that is equal to the name of the multidimensional array. It points the first element of the array of pointers. an array of pointer is declared with size of row number of the matrix, and each element points another array with the same data type the multi dimensional array declared.

Array of Pointers int list[5][3] ={1,3,5,7,9,11,13,15,17,19,21,23,25,27,29}; An array of pointers 1 3 5 list 7 9 11 13 15 17 19 21 23 25 27 29 A group of array of integers

Array of Pointers The use of multidimensional arrays with pointers: To access the element of x[2][5] you can say *(x[2]+5) or *(*(x+2)+5). Example : #include <stdio.h> #include <alloc.h> void main() { int *list[3], j, k; /* Declaration of the multi-dim. array*/ for (j=0; j<3; j++) list[j]=(int*) alloc(5*sizeof(int)); /* Reading numbers into multi-dim arr.*/ for (j=0; j<3;j++) for (k=0; k<5; k++) { printf(“number = “); scanf(“%d”,(*list+j)+k); } /* Writing the content of the arr.*/ for(j=0;j<3;j++) { printf(“\n”); for(k=0;k<5;k++) printf(“%5d “,*(*(list+j)+k)); } /* End of main()*/

Array of Pointers Array of pointers are mostly used with strings. e.g.: (Dynamically created array of strings with fixed string length) #include <stdio.h> #include <alloc.h> void main() { char *list[10]; int i; /* Declaration of the dynamic array*/ for (i=0; i<10; i++) list[i]= (char *) malloc( 21 * sizeof(char)); /* filling up the array*/ { printf(“Enter the name %d :”,i+1); scanf(“%s”,list[i]); } /* rewriting names in reverse entry order*/ for (i=9; i>=0; i--) printf(“\n %s”,list[i]); }

Array of Pointers e.g.: (Dynamically created array of strings with variable string length) #include <stdio.h> #include <alloc.h> int strlen( char* ); void main() { char *list[10], line[81]; int i, j, len; for (i=0; i<10; i++) { printf(“\n Enter the name %d =”, i+1); gets(line); len = strlen(line); list[i]= (char *) malloc( len * sizeof(char)); /* copy line to list[i]*/ for (j=0; j<len; j++) *(list[i]+j) = *(line+j); /* rewriting names in reverse entry order*/ for (i=9; i>=0; i--) printf(“\n %s”,list[i]); }

Array of Pointers e.g.: (Dynamically created array of strings with variable string length) //<< Continues >> int strlen( char *pstr ); { int slen=0; for (; *pstri!=‘\0’; pstr++) slen++; return (slen+1) }