Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.
|
|
- Chester Mathews
- 5 years ago
- Views:
Transcription
1 When a program is run, memory space is immediately reserved for the variables defined in the program. This memory space is kept by the variables until the program terminates. These variables are called static variables they exist throughout the program. In some cases, however, certain variables are used only at some point, say at the beginning of the program. But since they exist until the program terminates, we can say that memory is not used efficiently because the variables still occupy memory space even when they are no longer needed. Wouldn t it be a great idea to be able to dispose the variables (and thus recover memory space) at some point in the program when they are no longer necessary? Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.
2 This module discusses dynamic variables variables that are created and disposed during program execution. It s possible to create dynamic variables at some point in the program, and destroy it later when they are no longer needed. The main purpose of using dynamic variables is to conserve main memory space and use it efficiently.
3 Before we start discussing how to create dynamic variables, it could be helpful to have a short discussion on how the operating system (if you forgot what an operating system is, review module 1) manages the main memory. The main memory is finite, and the operating system keeps track of the memory locations that are currently being used by programs running, and those that are not being used (called free memory). When a new program is started, its variables are assigned to some free memory locations, and these memory locations are then classified as used. When the program terminates, these memory locations become free again.
4 free free used A used A used B used B free used num1 free used num2 free used temp free used temp free free (a) Before program execution (b) While program is being executed Figure 9.1 Variables in main memory
5 #include <stdio.h> int num1, num2; main() { program statements here } Figure 9.2 Sample program
6 Figure 9.1 shows a conceptual view of a portion of the main memory before and while the program in Figure 9.2 is running. The memory addresses are left out. Each memory location is marked either free or used. Initially, the figure shows three variables, A, B and temp, using up memory space. These locations are marked used, and the rest are free. When the program is started, the operating system looks for two free memory locations and assigns variables num1 and num2 in those locations. Subsequently, these locations are marked used.
7 When the program terminates, the memory locations assigned to num1 and num2 are marked free again. Managing used and free memory is only one of the functions of the operating system. It also does other things like coordinating computer devices such as printers and hard disks.
8 The only way to refer to a dynamic variable is through a pointer, so if we are to create a dynamic variable in the program, we have to define a pointer. The pointer and the dynamic variable to be created must have matching types, so if we intend to create a dynamic integer variable, a pointer to an integer must be defined.
9 A dynamic variable can be created by making a function call to malloc, a standard function. It s prototype is void *malloc(size_t n); The parameter n is of type size_t. size_t is a special data type you can think of it as a data type that can store a very large integer value. So parameter n is actually an integer. When the function is called, it searches for n bytes of free memory space and reserves it (i.e., mark it used ) for a dynamic variable. It returns a pointer to the memory space reserved. If there is not enough free memory for n bytes, it returns NULL, a constant pointer value. The dynamic variable created by malloc does not have any name, so the pointer returned must be assigned to a pointer variable so that it can be accessed later.
10 For example, let s create a dynamic integer variable. We ll need a pointer to an integer, say p, declared as int *p; Assuming that the size of an integer variable is four bytes, the statement p = (int *) malloc(4); creates a dynamic variable. As you can see, a type cast is used since malloc returns a pointer type void *. And to store and retrieve values to/from the dynamic variable, we use the indirection operator * on p, so *p = 17; stores 17 in the variable p.
11 You might be wondering how many bytes do the other data types consist of. Actually, the size of data types vary in different computer systems. On some systems, the int type is 4 bytes; while on others, it s 8 bytes. To make your program work on different systems, C provides a unary operator called sizeof which gives the size (in bytes) of a specified type. Its usage is sizeof(type-name)
12 So, the statement above that calls malloc can be equally written as p = (int *) malloc(sizeof(int)); Note that the value 4 was replaced here with sizeof(int). As another example, the statements below create a dynamic float variable, stores 0.5 in it, and outputs it. float t; t = (float *) malloc(sizeof(float)); *t = 0.5; printf( %f, *t);
13 A dynamic variable can also be a structure type. Below is an example. typedef struct account { int number; float balance; } acct; acct p; p = (acct *) malloc(sizeof(acct)); p->number = 1012; p->balance = ; In the program, p is a pointer to an acct type. The structure has two fields: number and balance. A dynamic structure variable is created, where the values 1012 and are stored. Conceptually, we can view the dynamic struct variable as p
14 The left box is the number field, while the right box is balance. The dynamic variable is pointed to by p, and so we may access its fields as p->number and p->balance. When a dynamic variable is no longer needed, it can be disposed (or destroyed) using the standard function free. The statement free(p); disposes the dynamic variable pointed to by p. The memory space pointed to becomes free again, and p no longer points to any variable.
15 Thus, it would be an error to assign values to *p. And by the way, whenever we use malloc and free in a program, we have to place #include <stdlib.h> at the beginning of the program. The file stdlib.h contains the function prototypes of malloc, free, and other built-in functions, and for the functions to work properly in your program, you have to include stdio.h.
16 The sample programs presented in the previous section were designed to illustrate how dynamic variables are created; such programs are hardly found in real-life applications. Actually, the main purpose of using dynamic variables is to make programs flexible in storing any size of data. To achieve this, dynamic variables are used to form complex data structures. These so-called complex structures are made up of self-referential structures interconnected with each other.
17 What is a self-referential structure? It is a structure that contains as field a pointer to a structure similar to itself. Below is a definition of a self-referential structure. struct node { int x; struct node *ptr; }; struct node has two fields: an integer, and a pointer to a struct node. Isn t the definition circular? Well, it is, and C allows that. Now, let s continue with the program and examine some statements.
18 struct node A, B; A.x = 10; B.x = 20; A.ptr = &B; Two variables, A and B, are defined as type struct node. The statement A.x= 10; stores 10 in the integer field of variable A, while the statement B.x =20; stores 20 in B. The last statement makes the pointer field of A point to B.
19 Conceptually, the variables can be pictured as A B Having made the pointer field of variable A point to B, B can now be referred to as *(A.ptr). So the expressions B.x and *(A.ptr).x now refer to the same variable. Alternatively, we can also use A.ptr->x. The statement A.ptr->x = 25; replaces the value 20 with 25.
20 Variable B also has a pointer field for which we have not stored any address yet. We can make it point to A with the statement B.ptr = &A; Here s a diagram showing how the variables look like after the two previous statements A B
21 Did you note that we can actually make a variable point to itself? The statement A.ptr = &A; makes the pointer field of A point to A: 10 A In this case, the expressions A.x, A.ptr->x and A.ptr->ptr->x all refer to the same variable.
22 The primary use of dynamic variables is to form flexible structures whose size can expand or shrink to accommodate varying data sizes. Consider for example the task of writing a program that maintains a list of hotel reservations. A reservation consists of the customer s name, room size, and perhaps the expected date of arrival. The program should allow reservations to be added and deleted from the list. Now, what type of data structure would you use to store the list of reservations? An array? Probably not, because the list has no fixed size and so we wouldn t know how large an array to define.
23 A data structure appropriate for the problem just mentioned is a linked list. A linked list consists of several dynamic variables linked together to form a chain-like structure (Figure 9.1). head data data data NULL Fig. 9.1 A linked list
24 As shown in Figure 9.1, the dynamic variables that make up the linked list are structures, each consisting of one (or more) field that stores data and another field variable head is a pointer variable that points to the first node. This pointer is needed because dynamic variables don t have names. The only way to refer to them is through a pointer. The pointer field of the last node is NULL, denoting the end of the linked list. A pointer field having a NULL value does not point to any memory location.
25 To illustrate, let s build a linked list to store the integers 3, 20, 8, 5. We ll need the following type and variable definitions: struct node { }; int x; struct node *next; typedef struct node nd; nd *head, *p;
26 Note that the data field here is of type integer. Here, struct node is self-referential, and head and p are pointers to struct node. To build the linked list, the first task is to create the first node. This is done by making a function call to malloc: head = (nd *) malloc(sizeof(nd)); head now points to a newly-created dynamic variable, where we store 3 using the statement head->x = 3;
27 At this point, we can picture our linked list as head 3 The following statements create the second node and stores 20 in it. The linked list is drawn after each statement. head->next = (nd *) malloc(sizeof(nd)); head 3 head->next->x = 20; head 3 20
28 Alternatively, we can use the other pointer variable, p, to effectively create the second node. The two statements above can be equally written as p = head; p->next = (nd *) malloc(sizeof(nd)); p->next->x = 20; The first statement, p = head; makes p point to where head points (which is, to the first node). The expression p->next then refer to the pointer field of the node (the first node) pointed to by p.
29 The idea of using p as an auxillary pointer might seem senseless at this point, but as you ll see below, this leads to a more compact code. Assuming p now points to the first node, the following statements create the third and fourth nodes: p = p->next; p->next = (nd *) malloc(sizeof(nd)); p->next->x = 8; p = p->next; p->next = (nd *) malloc(sizeof(nd)); p->next->x = 5; p = p->next; p->next = NULL;
30 The statement p = p->next; makes p point to the node following the node it currently points to. The last statement, p->next = NULL; assigns a NULL value to the pointer field of the last node. This is necessary so that later, when we try to output the values stored in the linked list, we ll know when to stop.
31 If you still find the discussion confusing, then, maybe a little illustration will help. The statements to create the linked list are written again below, together with a pictorial view of the linked list after each statement. head = (nd *) malloc(sizeof(nd)); head head->x = 3; head 3
32 p = head; head 3 p p->next = (nd *) malloc(sizeof(nd)); head 3 p p->next->x = 20; head p 3 20
33 p = p->next; head 3 20 p->next = (nd *) malloc(sizeof(nd)); head 3 20 p->next->x = 8; p p head p
34 p = p->next; head p->next = (nd *) malloc(sizeof(nd)); p head 3 20 p->next->x = 5; p = p->next; p->next = NULL; head p 8 5 NULL p
35 Let s discuss some common operations that are usually done on linked lists. These are: (1) building a linked list, (2) outputting contents of the list, (3) inserting a data item into the list, (4) deleting a data item from the list, and (5) disposing the linked list.
36 The previous section showed how to store a list of four integers (3, 20, 8 and 5) in a linked list. The entire code is again given below. head = (nd *) malloc(sizeof(nd)); head->x = 3; p = head; p->next = (nd *) malloc(sizeof(nd)); p->next->x = 20; p = p->next; p->next = (nd *) malloc(sizeof(nd)); p->next->x = 8; p = p->next; p->next = (nd *) malloc(sizeof(nd)); p->next->x = 5; p = p->next; p->next = NULL;
37 Do you notice that the 4th, 5th and 6th statements are successively repeated? What do the statements actually do? It creates a dynamic variable, stores a value in it, and moves the pointer p. The three statements are repeated three times to create the second, third and fourth node. The repeated occurrence of these statements suggests that they can be placed in the loop.
38 In general, the program would then look like head = (nd *) malloc(sizeof(nd)); head->x = data; p = head; while there is data { p->next = (nd *) malloc(sizeof(nd)); p->next->x = data; p = p->next; } p->next = NULL; The statements before the while loop creates the first node. data can either be inputted, in which case we use an input function like scanf, or it can be obtained from other variables such as an array.
39 Let s do the task of storing integers 1-10 in a linked list. This is accomplished by the statements below. head = (nd *) malloc(sizeof(nd)); head->x = 1; p = head; for (i=2; i<=10; i++) { p->next = (nd *) malloc(sizeof(nd)); p->next->x = i; p = p->next; } p->next = NULL; The second statement stores the value 1 in the first node. The for loop takes care of the rest of the values (2-10). Note that the control variable, i, is initialized to 2 and is incremented until it reaches 10.
40 One way to output data stored in the linked list is to list down the data fields of the nodes, as in printf( %d\n, head->x); printf( %d\n, head->next->x); printf( %d\n, head->next->next->x); This method, however, is impractical because if the list is long, we ll be listing down a lot of statements. A better way is to use a loop, just like what we did when building the linked list.
41 The program code to output the integers stored in the linked list is shown below: p = head; while (p!= NULL) { printf( %d\n, p->x); p = p->next; } The idea is to let a pointer, p in this case, move starting from the first node up to the last node of the linked list. And as it moves, the data field of the node pointed to by p is outputted. The first statement makes p point to the first node. Then, the while statement tests if p is NULL, because if so, the end of the list has been reached.
42 To insert a new data item into the linked list, four things have to be done: 1. Create a new node (a dynamic variable). 2. Store the data value in the newly created node. 3. Locate the position in the linked list where the new node is to be inserted. 4. Manipulating the pointers to cause the insertion.
43 Let s have an example. Suppose that we would like to insert the data value 0 at the beginning of our linked list containing integers 1 to 10. To do this, we ll need an additional pointer, nd *temp; The first two steps are accomplished by the statements below. A pictorial view of the dynamic variable is also shown. temp = (nd *) malloc(sizeof(nd)); temp->x = 0; temp 0
44 In the next step (step 3), we need to locate the position where we are to insert the new node. But since we are inserting at the beginning of the linked list, we need not locate this position since head always points to the first node. To accomplish step 4, we simply make head point to the new node, and let the new node s pointer field point to the node previously pointed to by head. The sequence of statements needed to do these is given below, together with the pictorial view of the linked list after each statement.
45 p = head; temp 0 head p 1 2 head = temp; temp head p 0 1 2
46 temp->next = p; temp head p Note that head now points to the new node. Also note that the statement p = head; is necessary. If we don t do this, there s no way we can refer to the node containing 1 once we have changed head to point to the new node.
47 To summarize, the complete set of statements to insert 0 at the beginning of the linked list is given below. temp = (nd *) malloc(sizeof(nd)); temp->x = 0; p = head; head = temp; temp->next = p;
48 The program statements that insert an item at the middle of the list are quite different from those that insert at the beginning of the list. This is because when we insert at the middle, we don t need to change where head points. Also, we need to locate the proper place to insert the item. For example, suppose we would like to insert 0 after 5 instead of at the beginning. To do this, we first create a new node in the same way we did before (that was done by the first two statements).
49 temp = (nd *) malloc(sizeof(nd)); temp->x = 0; temp 0 Then, we locate the node after which the new node will be inserted. This node is the one that contains 5, and we make p point to it: temp p
50 This locate and point process can be accomplished by the program code below: p = head; while (p->x!= 5) p = p->next; Then, we execute the following statements: temp->next = p->next; temp p
51 p->next = temp; temp p As shown, the first statement makes the pointer field of the node to be inserted point to the node it is supposed to follow, and the second statement points the pointer field of the node containing 5 to the new node. For these two statements to work, the prerequisite is to have p pointing to the node that would precede the new data item to be inserted.
52 Let s write a function called insert_list that inserts an integer into the linked list whose data items are in ascending order. When the function inserts a new integer, the integer should be inserted in the proper place so that the ascending order is maintained. The function is given below. It has two parameters: the head of the linked list and the integer to be inserted.
53 void insert_list(nd *head, int num) { nd *p, temp; temp = (nd *) malloc(sizeof(nd)); temp->x = num; p = head; if (num < head->x) /* insert at beginning */ { head = temp; temp->next = p; } else { /* locate proper place */ while (num > p->next->x && p->next!= NULL) p = p->next; /* insert node */ temp->next = p->next; p->next = temp; }
54 The first two statements create a new node to be inserted. Then, the if statement tests if the first data item in the linked list is greater than num. If so, the new node is inserted at the start of the list, so as to maintain the ascending order of the data items. Otherwise, the proper place to insert is searched by going through the data items until either an item not less than num is found or the end of the linked list is reached. The node is then inserted in the manner discussed previously.
55 Deleting a node from a linked list involves two steps: (1) changing the pointers so that the node is effectively removed from the list, and (2) disposing the node removed using the free function. Like insertion, we differentiate the case of deleting a node at the beginning of the linked list from that of deleting at the middle.
56 The following statements delete the first node of the linked list. temp = head; head temp 1 2 head = temp->next; head temp 1 2 free(temp); head temp 2
57 The last statement destroys the dynamic variable, and temp now points to nowhere. As discussed previously, it s important to destroy dynamic variables that are no longer used since they occupy memory space. To delete a node at the middle or end of the list, we ll need a pointer, say p, that points to the node preceding the node to be deleted. For example, if we d like to delete the node containing 5 from the linked list, we have to make p point to the node containing 4, as shown below.
58 p To achieve this, we can use the locate and point program code presented when we discussed insertion in the previous subsection. After making p point to the proper place, we then manipulate the pointers to remove the node from the list. This is accomplished by the following statements.
59 temp = p->next; p p->next = p->next->next; p free(temp); p temp temp 4 6 temp Let s write another function, delete_list, that deletes a data item from the list. This is shown below.
60 void delete_list(nd *head, int num) { nd *p, *temp; /* check if list is empty */ if (head == NULL) return; if (num == head->x) /* delete first node */ { temp = head; head = head->next; free(temp); } else { /* search node to delete */ p = head; while (num!= p->next->x && p->next!= NULL) p = p->next; if (p->next!= NULL)
61 } } /* node is found, so delete it */ { temp = p->next; p->next = p->next->next; free(temp); } Note that at the beginning of the function, we first check if the linked list is empty. If so, we immediately exit from the function by executing a return; statement.
62 Variables that are defined in the program are referred to as static variables they exist throughout the program. C provides another type of variable called dynamic variables these variables can be created at some point in the program and destroyed when they are no longer needed. By using dynamic variables, memory space is efficiently utilized because they can be destroyed when no longer needed. In most applications, dynamic variables are used to store data that vary in size. Complex data structures are built by interconnecting dynamic variables. One such structure is the linked list. A linked list is a collection of self-referential dynamic variables interconnected to form a chain-like structure. It s used to store a list of data items, and items can be inserted and deleted from the linked list. And since linked lists are made up of dynamic variables, it can expand or shrink to accommodate any data size.
Chapter 2 (Dynamic variable (i.e. pointer), Static variable)
Chapter 2 (Dynamic variable (i.e. pointer), Static variable) August_04 A2. Identify and explain the error in the program below. [4] #include int *pptr; void fun1() { int num; num=25; pptr= #
More informationAt the end of this module, the student should be able to:
INTRODUCTION One feature of the C language which can t be found in some other languages is the ability to manipulate pointers. Simply stated, pointers are variables that store memory addresses. This is
More informationData Structure Series
Data Structure Series This series is actually something I started back when I was part of the Sweet.Oblivion staff, but then some things happened and I was no longer able to complete it. So now, after
More informationCS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018
CS 31: Intro to Systems Pointers and Memory Kevin Webb Swarthmore College October 2, 2018 Overview How to reference the location of a variable in memory Where variables are placed in memory How to make
More informationHeap Arrays and Linked Lists. Steven R. Bagley
Heap Arrays and Linked Lists Steven R. Bagley Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index Variables and arrays have a type Create our
More informationFirst of all, it is a variable, just like other variables you studied
Pointers: Basics What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the address (rather than the value)
More informationCS113: Lecture 5. Topics: Pointers. Pointers and Activation Records
CS113: Lecture 5 Topics: Pointers Pointers and Activation Records 1 From Last Time: A Useless Function #include void get_age( int age ); int age; get_age( age ); printf( "Your age is: %d\n",
More informationIn Java we have the keyword null, which is the value of an uninitialized reference type
+ More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are
More informationElementary Data Structures: Part 1: Arrays, Lists. CSE 2320 Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington
Elementary Data Structures: Part 1: Arrays, Lists CSE 2320 Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1 Basic Types Types like integers, real numbers, characters.
More informationDarshan Institute of Engineering & Technology for Diploma studies Unit 4
Pointer A pointer is a variable that contains address or location of another variable. Pointer is a derived data type in C. Pointers contain memory address as their values, so they can also be used to
More informationLinked Lists. .. and other linked structures. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
1 Linked Lists.. and other linked structures Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Dynamic memory allocation: review typedef struct { int hitemp;
More informationC Programming Language: C ADTs, 2d Dynamic Allocation. Math 230 Assembly Language Programming (Computer Organization) Thursday Jan 31, 2008
C Programming Language: C ADTs, 2d Dynamic Allocation Math 230 Assembly Language Programming (Computer Organization) Thursday Jan 31, 2008 Overview Row major format 1 and 2-d dynamic allocation struct
More informationUnderstanding Pointers
Division of Mathematics and Computer Science Maryville College Pointers and Addresses Memory is organized into a big array. Every data item occupies one or more cells. A pointer stores an address. A pointer
More informationChapter 7. Pointers. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
1 Chapter 7 Pointers Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 7 - Pointers 7.1 Introduction 7.2 Pointer Variable Definitions and Initialization
More informationMODULE 5: Pointers, Preprocessor Directives and Data Structures
MODULE 5: Pointers, Preprocessor Directives and Data Structures 1. What is pointer? Explain with an example program. Solution: Pointer is a variable which contains the address of another variable. Two
More informationLecture 04 Introduction to pointers
Lecture 04 Introduction to pointers A pointer is an address in the memory. One of the unique advantages of using C is that it provides direct access to a memory location through its address. A variable
More informationCS24 Week 2 Lecture 1
CS24 Week 2 Lecture 1 Kyle Dewey Overview C Review Void pointers Allocation structs void* (Void Pointers) void* Like any other pointer, it refers to some memory address However, it has no associated type,
More informationLinked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links
Linked-List Basic Examples A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links Accessed via a pointer to the first node of the list Subsequent
More informationMARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100
FINAL EXAMINATION INTRODUCTION TO ALGORITHMS AND PROGRAMMING II 03-60-141-01 U N I V E R S I T Y O F W I N D S O R S C H O O L O F C O M P U T E R S C I E N C E Winter 2014 Last Name: First Name: Student
More informationC Structures & Dynamic Memory Management
C Structures & Dynamic Memory Management Goals of this Lecture Help you learn about: Structures and unions Dynamic memory management Note: Will be covered in precepts as well We look at them in more detail
More informationMM1_ doc Page E-1 of 12 Rüdiger Siol :21
Contents E Structures, s and Dynamic Memory Allocation... E-2 E.1 C s Dynamic Memory Allocation Functions... E-2 E.1.1 A conceptual view of memory usage... E-2 E.1.2 malloc() and free()... E-2 E.1.3 Create
More informationPointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017
Pointers (part 1) EECS 2031 25 September 2017 1 What are pointers? We have seen pointers before. scanf( %f, &inches );! 2 1 Example char c; c = getchar(); printf( %c, c); char c; char *p; c = getchar();
More informationFOR Loop. FOR Loop has three parts:initialization,condition,increment. Syntax. for(initialization;condition;increment){ body;
CLASSROOM SESSION Loops in C Loops are used to repeat the execution of statement or blocks There are two types of loops 1.Entry Controlled For and While 2. Exit Controlled Do while FOR Loop FOR Loop has
More informationAPS105. Structures 11/18/2013. Example A struct of stock items at a store: Structures. Lists. Arrays allow a collection of elements
APS105 Lists Structures Textbook Chapters 10.1, 10.3, 10.4, 10.6 2 Structures Arrays allow a collection of elements All of the same type How to collect elements of different types? Structures; in C: struct
More informationHeap Arrays. Steven R. Bagley
Heap Arrays Steven R. Bagley Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index a[42] = 35; Variables and arrays have a type int, char, double,
More informationAssist. Prof. Dr. Caner ÖZCAN
Assist. Prof. Dr. Caner ÖZCAN Memory Structure When a variable defined it is stored somewhere in memory. Memory can be thought as block consist of cells. When a variable defined, required number of cell
More informationECE 2400 Computer Systems Programming Fall 2017 Topic 4: C Pointers
ECE 2400 Computer Systems Programming Fall 2017 Topic 4: C Pointers School of Electrical and Computer Engineering Cornell University revision: 2017-09-23-11-06 1 Pointer Basics 2 2 Call by Value vs. Call
More informationPointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays
EE105: Software Engineering II Part 6 Pointers page 1 of 19 Part VI Pointers 1) Introduction 2) Declaring Pointer Variables 3) Using Pointers 4) Pointer Arithmetic 5) Pointers and Arrays 6) Pointers and
More informationEM108 Software Development for Engineers
EE108 Section 6 Pointers page 1 of 20 EM108 Software Development for Engineers Section 6 - Pointers 1) Introduction 2) Declaring Pointer Variables 3) Using Pointers 4) Pointer Arithmetic 5) Pointers and
More informationDynamic Memory Allocation and Linked Lists
CSE 2421: Systems I Low-Level Programming and Computer Organization Dynamic Memory Allocation and Linked Lists Presentation I Read/Study: Reek Chapter 11 & 12 Gojko Babić 02-26-2017 Functions malloc and
More informationAt this time we have all the pieces necessary to allocate memory for an array dynamically. Following our example, we allocate N integers as follows:
Pointers and Arrays Part II We will continue with our discussion on the relationship between pointers and arrays, and in particular, discuss how arrays with dynamical length can be created at run-time
More informationAdvanced Pointer Topics
Advanced Pointer Topics Pointers to Pointers A pointer variable is a variable that takes some memory address as its value. Therefore, you can have another pointer pointing to it. int x; int * px; int **
More informationStructures. Basics of Structures (6.1) EECS l Now struct point is a valid type. l Defining struct variables: struct point { int x; int y; };
Structures EECS 2031 25 September 2017 1 Basics of Structures (6.1) struct point { int x; int y; keyword struct introduces a structure declaration. point: structure tag x, y: members The same member names
More informationOutline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary
Pointers 1 2 Outline Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary 3 Computer Memory Revisited Computers store data in memory slots Each slot has an
More informationContent. In this chapter, you will learn:
ARRAYS & HEAP Content In this chapter, you will learn: To introduce the array data structure To understand the use of arrays To understand how to define an array, initialize an array and refer to individual
More informationC Pointers. Indirection Indirection = referencing a value through a pointer. Creating Pointers. Pointer Declarations. Pointer Declarations
55:017, Computers in Engineering C Pointers C Pointers Powerful C feature but challenging to understand Some uses of pointers include Call by reference parameter passage Dynamic data structures Data structures
More informationCS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016
CS 31: Intro to Systems Pointers and Memory Martin Gagne Swarthmore College February 16, 2016 So we declared a pointer How do we make it point to something? 1. Assign it the address of an existing variable
More informationCA341 - Comparative Programming Languages
CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data
More informationLinked List. April 2, 2007 Programming and Data Structure 1
Linked List April 2, 2007 Programming and Data Structure 1 Introduction head A linked list is a data structure which can change during execution. Successive elements are connected by pointers. Last element
More informationGoals of this Lecture
C Pointers Goals of this Lecture Help you learn about: Pointers and application Pointer variables Operators & relation to arrays 2 Pointer Variables The first step in understanding pointers is visualizing
More informationThe C Programming Language Part 4. (with material from Dr. Bin Ren, William & Mary Computer Science, and
The C Programming Language Part 4 (with material from Dr. Bin Ren, William & Mary Computer Science, and www.cpp.com) 1 Overview Basic Concepts of Pointers Pointers and Arrays Pointers and Strings Dynamic
More information(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University
(13-2) Dynamic Data Structures I H&K Chapter 13 Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University Dynamic Data Structures (1) Structures that expand and contract
More informationCS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor
CS 261 Fall 2017 Mike Lam, Professor C Introduction Variables, Memory Model, Pointers, and Debugging The C Language Systems language originally developed for Unix Imperative, compiled language with static
More informationData Structures and Algorithms (DSA) Course 5 Lists. Iulian Năstac
Data Structures and Algorithms (DSA) Course 5 Lists Iulian Năstac Cap. Lists (recapitulation) 1. Introduction Linked lists are the best and simplest example of a dynamic data structure that uses pointers
More informationSubject: Fundamental of Computer Programming 2068
Subject: Fundamental of Computer Programming 2068 1 Write an algorithm and flowchart to determine whether a given integer is odd or even and explain it. Algorithm Step 1: Start Step 2: Read a Step 3: Find
More informationHigh Performance Programming Programming in C part 1
High Performance Programming Programming in C part 1 Anastasia Kruchinina Uppsala University, Sweden April 18, 2017 HPP 1 / 53 C is designed on a way to provide a full control of the computer. C is the
More informationDynamically Allocated Memory in C
Dynamically Allocated Memory in C All throughout the C course (COP 3223), all examples of variable declarations were statically allocated memory. The word static means not changing while the word dynamic
More informationC Review. MaxMSP Developers Workshop Summer 2009 CNMAT
C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***
More informationCS61, Fall 2012 Section 2 Notes
CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors
More informationChapter 14. Dynamic Data Structures. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.
Chapter 14 Dynamic Data Structures Instructor: Öğr. Gör. Okan Vardarlı Copyright 2004 Pearson Addison-Wesley. All rights reserved. 12-1 Dynamic Data Structure Usually, so far, the arrays and strings we
More informationDECLARAING AND INITIALIZING POINTERS
DECLARAING AND INITIALIZING POINTERS Passing arguments Call by Address Introduction to Pointers Within the computer s memory, every stored data item occupies one or more contiguous memory cells (i.e.,
More informationIntermediate Programming, Spring 2017*
600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general
More informationC Introduction. Comparison w/ Java, Memory Model, and Pointers
CS 261 Fall 2018 Mike Lam, Professor C Introduction Comparison w/ Java, Memory Model, and Pointers Please go to socrative.com on your phone or laptop, choose student login and join room LAMJMU The C Language
More informationby Pearson Education, Inc. All Rights Reserved.
Let s improve the bubble sort program of Fig. 6.15 to use two functions bubblesort and swap. Function bubblesort sorts the array. It calls function swap (line 51) to exchange the array elements array[j]
More informationJTSK Programming in C II C-Lab II. Lecture 3 & 4
JTSK-320112 Programming in C II C-Lab II Lecture 3 & 4 Xu (Owen) He Spring 2018 Slides modified from Dr. Kinga Lipskoch Planned Syllabus The C Preprocessor Bit Operations Pointers and Arrays (Dynamically
More informationSelf-referential Structures and Linked List. Programming and Data Structure 1
Self-referential Structures and Linked List Programming and Data Structure 1 Linked List :: Basic Concepts A list refers to a set of items organized sequentially. An array is an example of a list. The
More informationLecture 8 Dynamic Memory Allocation
Lecture 8 Dynamic Memory Allocation CS240 1 Memory Computer programs manipulate an abstraction of the computer s memory subsystem Memory: on the hardware side 3 @ http://computer.howstuffworks.com/computer-memory.htm/printable
More informationCOMP26120: Pointers in C (2018/19) Lucas Cordeiro
COMP26120: Pointers in C (2018/19) Lucas Cordeiro lucas.cordeiro@manchester.ac.uk Organisation Lucas Cordeiro (Senior Lecturer, FM Group) lucas.cordeiro@manchester.ac.uk Office: 2.44 Office hours: 10-11
More informationLinked List in Data Structure. By Prof. B J Gorad, BECSE, M.Tech CST, PHD(CSE)* Assistant Professor, CSE, SITCOE, Ichalkaranji,Kolhapur, Maharashtra
Linked List in Data Structure By Prof. B J Gorad, BECSE, M.Tech CST, PHD(CSE)* Assistant Professor, CSE, SITCOE, Ichalkaranji,Kolhapur, Maharashtra Linked List Like arrays, Linked List is a linear data
More informationCpt S 122 Data Structures. Data Structures
Cpt S 122 Data Structures Data Structures Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Introduction Self Referential Structures Dynamic Memory Allocation
More informationAnnouncements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1
Announcements assign due tonight No late submissions Labs start this week Very helpful for assign1 Goals for Today Pointer operators Allocating memory in the heap malloc and free Arrays and pointer arithmetic
More informationName :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70
Name :. Roll No. :..... Invigilator s Signature :.. 2011 INTRODUCTION TO PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give
More informationCSC 270 Survey of Programming Languages. What is a Pointer?
CSC 270 Survey of Programming Languages C Lecture 6 Pointers and Dynamic Arrays What is a Pointer? A pointer is the address in memory of a variable. We call it a pointer because we envision the address
More information2/28/2018. Overview. The C Programming Language Part 4. Pointers. Pointers. Pointers. Pointers
Overview The C Programming Language Part 4 (with material from Dr. Bin Ren, William & Mary Computer Science, and www.cpp.com) Basic Concepts of and Arrays and Strings Dynamic Memory Allocation 1 2 pointer
More informationESc101: (Linear, Circular, Doubly) Linked Lists, Stacks, Queues, Trees. Introduction to Linked Lists
ESc101: (Linear, Circular, Doubly) Linked Lists, Stacks, Queues, Trees Instructor: Krithika Venkataramani Semester 2, 2011-2012 1 Introduction to Linked Lists Each bead connected to the next through a
More informationCS 11 C track: lecture 5
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap Pointers (from last week) Address: location where data stored
More informationUnit 7. Functions. Need of User Defined Functions
Unit 7 Functions Functions are the building blocks where every program activity occurs. They are self contained program segments that carry out some specific, well defined task. Every C program must have
More informationThe time and space are the two measure for efficiency of an algorithm.
There are basically six operations: 5. Sorting: Arranging the elements of list in an order (either ascending or descending). 6. Merging: combining the two list into one list. Algorithm: The time and space
More informationCS61C : Machine Structures
inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 4 Introduction to C (pt 2) 2014-09-08!!!Senior Lecturer SOE Dan Garcia!!!www.cs.berkeley.edu/~ddgarcia! C most popular! TIOBE programming
More informationLinked Data Representations
Linked Data Representations Manolis Koubarakis 1 Linked Data Representations Linked data representations such as lists, stacks, queues, sets and trees are very useful in computer science and applications.
More informationBinary Trees. Height 1
Binary Trees Definitions A tree is a finite set of one or more nodes that shows parent-child relationship such that There is a special node called root Remaining nodes are portioned into subsets T1,T2,T3.
More informationECE551 Midterm Version 1
Name: ECE551 Midterm Version 1 NetID: There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual
More informationCS132 Algorithm. Instructor: Jialiang Lu Office: Information Center 703
CS132 Algorithm Instructor: Jialiang Lu Email: jialiang.lu@sjtu.edu.cn Office: Information Center 703 Chapter 3 STRUCTURES IN C 2 Structures Introduction Collections of related variables (aggregates) under
More informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers
More informationC: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21
Department of Computer Science College of Engineering Boise State University September 11, 2017 1/21 Pointers A pointer is a variable that stores the address of another variable. Pointers are similar to
More informationCS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017
CS 137 Part 8 Merge Sort, Quick Sort, Binary Search November 20th, 2017 This Week We re going to see two more complicated sorting algorithms that will be our first introduction to O(n log n) sorting algorithms.
More informationPointers. Introduction
Pointers Spring Semester 2007 Programming and Data Structure 1 Introduction A pointer is a variable that represents the location (rather than the value) of a data item. They have a number of useful applications.
More informationC++ Programming Chapter 7 Pointers
C++ Programming Chapter 7 Pointers Yih-Peng Chiou Room 617, BL Building (02) 3366-3603 ypchiou@cc.ee.ntu.edu.tw Photonic Modeling and Design Lab. Graduate Institute of Photonics and Optoelectronics & Department
More informationIntroduction to C: Pointers
Introduction to C: Pointers Nils Moschüring PhD Student (LMU) Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 1 1 Introduction 2 Pointers Basics Useful: Function
More informationMYcsvtu Notes LECTURE 34. POINTERS
LECTURE 34 POINTERS Pointer Variable Declarations and Initialization Pointer variables Contain memory addresses as their values Normal variables contain a specific value (direct reference) Pointers contain
More informationCS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/
CS61C Machine Structures Lecture 4 C Structs & Memory Management 9/5/2007 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L04 C Structs (1) C String Standard Functions
More informationCS61C : Machine Structures
inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 C Memory Management 2007-06-28 Scott Beamer, Instructor iphone Comes out Tomorrow CS61C L4 C Memory Management (1) www.apple.com/iphone
More informationOutline. Briefly review the last class Pointers and Structs Memory allocation Linked lists
Outline Briefly review the last class Pointers and Structs Memory allocation Linked lists C Structures and Memory Allocation A struct is a data structure that comprises multiple types, each known as a
More informationDynamic Memory Management. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island
Dynamic Memory Management Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island 1 Dynamic Memory Allocation Dynamic memory allocation is used to
More informationVariation of Pointers
Variation of Pointers A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before
More informationReview: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc
CS61C L4 C Pointers (1) inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 C Strings, Arrays, & Malloc Albert Chae Instructor 2008-06-26 Review: C Strings A string in C is just an array
More informationSubject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100
Code: DC-05 Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100 NOTE: There are 11 Questions in all. Question 1 is compulsory and carries 16 marks. Answer to Q. 1. must be written in the space
More informationMemory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science
Memory Allocation in C C Programming and Software Tools N.C. State Department of Computer Science The Easy Way Java (JVM) automatically allocates and reclaims memory for you, e.g... Removed object is implicitly
More informationadvanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef
today advanced data types (1) typedef. mon 23 sep 2002 homework #1 due today homework #2 out today quiz #1 next class 30-45 minutes long one page of notes topics: C advanced data types dynamic memory allocation
More informationA. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS
Syllabus: Pointers and Preprocessors: Pointers and address, pointers and functions (call by reference) arguments, pointers and arrays, address arithmetic, character pointer and functions, pointers to pointer,initialization
More informationChapter 6 - Pointers
Chapter 6 - Pointers Outline 1 Introduction 2 Pointer Variable Declarations and Initialization 3 Pointer Operators 4 Calling Functions by Reference 5 Using the const Qualifier with Pointers 6 Bubble Sort
More informationDynamic memory allocation (malloc)
1 Plan for today Quick review of previous lecture Array of pointers Command line arguments Dynamic memory allocation (malloc) Structures (Ch 6) Input and Output (Ch 7) 1 Pointers K&R Ch 5 Basics: Declaration
More informationThe combination of pointers, structs, and dynamic memory allocation allow for creation of data structures
Data Structures in C C Programming and Software Tools N.C. State Department of Computer Science Data Structures in C The combination of pointers, structs, and dynamic memory allocation allow for creation
More informationLab 3. Pointers Programming Lab (Using C) XU Silei
Lab 3. Pointers Programming Lab (Using C) XU Silei slxu@cse.cuhk.edu.hk Outline What is Pointer Memory Address & Pointers How to use Pointers Pointers Assignments Call-by-Value & Call-by-Address Functions
More informationCS61C : Machine Structures
inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 5 C Memory Management Lecturer PSOE Dan Garcia www.cs.berkeley.edu/~ddgarcia CS61C L05 C Structures, Memory Management (1) 2005-01-28 The
More informationArrays and Pointers. CSE 2031 Fall November 11, 2013
Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example
More informationSYSC 2006 C Winter 2012
SYSC 2006 C Winter 2012 Pointers and Arrays Copyright D. Bailey, Systems and Computer Engineering, Carleton University updated Sept. 21, 2011, Oct.18, 2011,Oct. 28, 2011, Feb. 25, 2011 Memory Organization
More informationDynamic memory allocation
Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes
More informationArrays and Pointers (part 1)
Arrays and Pointers (part 1) CSE 2031 Fall 2012 Arrays Grouping of data of the same type. Loops commonly used for manipulation. Programmers set array sizes explicitly. Arrays: Example Syntax type name[size];
More informationC Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1
C Pointers 1. Objective... 2 2. Introduction... 2 3. Pointer Variable Declarations and Initialization... 3 4. Reference operator (&) and Dereference operator (*) 6 5. Relation between Arrays and Pointers...
More information