Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Similar documents
In Java we have the keyword null, which is the value of an uninitialized reference type

Incoming Exam. CS 201 Introduction to Pointers. What is a Pointer? Pointers and Addresses. High Speed Memory (RAM) Size of Variable Types.

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

Character Strings. String-copy Example

CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures

Memory Management. CSC215 Lecture

Memory Allocation. General Questions

Variation of Pointers

Class Information ANNOUCEMENTS

o Code, executable, and process o Main memory vs. virtual memory

Dynamic Memory Allocation and Linked Lists

First of all, it is a variable, just like other variables you studied

Dynamic Allocation in C

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Advanced Pointer Topics

Dynamic Data Structures. CSCI 112: Programming in C

A3-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH 'C' LANGUAGE

CSC 1600 Memory Layout for Unix Processes"

Dynamic Memory Allocation

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

Fundamental of Programming (C)

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Lab 3. Pointers Programming Lab (Using C) XU Silei

School of Science and Technology

Pointers, Dynamic Data, and Reference Types

DECLARAING AND INITIALIZING POINTERS

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

Programming. Pointers, Multi-dimensional Arrays and Memory Management

CS24 Week 2 Lecture 1

Dynamic Allocation in C

CS61, Fall 2012 Section 2 Notes

MODULE 5: Pointers, Preprocessor Directives and Data Structures

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Arrays and Pointers (part 2) Be extra careful with pointers!

Arrays and Pointers (part 2) Be extra careful with pointers!

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Language comparison. C has pointers. Java has references. C++ has pointers and references

Linked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size

CS 61c: Great Ideas in Computer Architecture

Darshan Institute of Engineering & Technology for Diploma studies Unit 4

2. In simple interest what sum amounts of Rs.1120/- in 4 years and Rs.1200/- in 5 years?

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

Dynamic memory allocation (malloc)

COP 3223 Introduction to Programming with C - Study Union - Spring 2018

Content. In this chapter, you will learn:

C Programming Basics II

Procedural programming with C

Fundamentals of Programming Session 19

Computer Programming Unit 3

Fall 2018 Discussion 2: September 3, 2018

CS61C : Machine Structures

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

C Structures & Dynamic Memory Management

CS61C : Machine Structures

ECE 15B COMPUTER ORGANIZATION

CS61C : Machine Structures

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Pointers, Arrays, Memory: AKA the cause of those Segfaults

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

Contents of Lecture 3

Unit IV & V Previous Papers 1 mark Answers

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0)

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)

EM108 Software Development for Engineers

PRINCIPLES OF OPERATING SYSTEMS

Programs in memory. The layout of memory is roughly:

The output will be: marks all or nothing. 1 #include <stdio.h> 2 main() { 3 int i; int j; 4 int *p; int *q; 6 p = &i; 7 q = &j; 8 i = 1;

Pointers and Memory Management

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

CS61C Machine Structures. Lecture 5 C Structs & Memory Mangement. 1/27/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Final Intro to C Review

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary

Data Structures Lecture 2 : Part 1: Programming Methodologies Part 2: Memory Management

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C PROGRAMMING Lecture 5. 1st semester

High Performance Programming Programming in C part 1


Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Tutorial 10 Pointers in C. Shuyue Hu

Fundamentals of Programming Session 20

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

Lecture 8 Dynamic Memory Allocation

Memory Organization. The machine code and data associated with it are in the code segment

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

More about BOOLEAN issues

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

Kurt Schmidt. October 30, 2018

CSE2301. Dynamic memory Allocation. malloc() Dynamic Memory Allocation and Structs

Chapter 14. Dynamic Data Structures. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

Transcription:

Chapter 2 (Dynamic variable (i.e. pointer), Static variable) August_04 A2. Identify and explain the error in the program below. [4] #include<stdio.h> int *pptr; void fun1() { int num; num=25; pptr= &num; } void main() { fun1(); //makes pptr point to somevalue. printf( value of *pptr: %d \n, *pptr); } Since num is a local variable, [1] when the call of fun1 terminates, num is deleted [1] So pptr is now pointing to the location [1] which no longer belongs to this program. [1] August_04 A5. (a) Explain each of the following terms, and give an example for each [6] (ii) Pointers Data type that holds a memory address [1] eg char *ptr; [1] (iii) Malloc Command to reserve/allocate memory location for a variable. [1] eg ptr = (char *) malloc(sizeof(char)); [1] 1

(b) Complete the following sentences with the most appropriate word or phrase. [2] (i) A/an variable is one whose size is fixed at compilation time and which cannot be created or destroyed during the compilation process. (ii) A/an identifies the first logical node in a linked list. (i) static [1] (ii) head pointer [1] (c) Answer the following questions by selecting the most appropriate answer from the list given. [3] (i) Which of the following defines a pointer variable to an integer? (A) int &ptr; (B) int &&ptr; (C) int *ptr; (D) int **ptr; (ii) Which of the following defines and initializes a pointer to the address of x? (A) int *ptr; = *x; (B) int *ptr = ^x; (C) int *ptr=&x; (D) int &ptr = *x; (iii) Which of the following statements assigns the value stored in x to the first element of an array, ary? (A) ary=x[0]; (B) ary= x[1]; (C) ary[0] =x; (D) ary[1] =x; (i) (C) int *ptr; [1] (ii) (C) int *ptr=&x; [1] (iii) (C) ary[0] =x; [1] (d) Briefly describe the process known as garbage collection and give an example of when it might be required. [4] Garbage collection is a process to keep track of those memory locations which contain data that is no longer in use [1] and freeing up such memory locations so they can be reused. [1] [1 mark for any correct example; 1 mark for clear explanation] e.g. void function() { int item=15; printf( %d, item); } The local variable, item, is created in the above function. Once the function is finished, the variable is no longer used. The memory space taken up by item will be freed. 2

August_04 B1 (b) (i) Explain three differences between static and dynamic variables. [6] Static Its size is fixed at compilation time [1] A certain memory location is reserved [1] Cannot be created and destroyed during the execution of the program [1] Dynamic Its size is not fixed at compilation time [1] No memory location is reserved [1] Can be created and destroyed during the execution of the program [1] (ii) Give two possible disadvantages of using a static data structure. [2] If you overestimate the size of the data structure, some memory is wasted. [1] If you underestimate the size of the data structure, you may be unable to process all the data, unless the program is modified. [1] (iii) Give one example each of static and dynamic data structures. [2] Static array [1] Dynamic Linked list [1] 3

April 04 4

5

April 04 6

December_03 A6. (a) What is wrong with the following code? [2] Answer: the pointer, str is not assigned with a valid memory spaces. [1] this is called an uninitialized pointer. [1] Remark: When a pointer is declared, it does not take up any memory space. If you want to use this pointer to store some data for you, you must use malloc to allocate some memory spaces before you use it to store data. (b) What has caused the above error? [2] Because it has been declared as a global variable. [2] December_03 B1. (c) (i) What is the purpose of NULL when used as a pointer in a C program? [2] Null does not reference a storage location but instead [1] denotes the pointer that does not point to anything. [1] (ii) Show how to assign the value NULL to a particular pointer ptr. [2] ptr = NULL; [mark breakdown] ptr and the assignment symbol (=) [1] NULL must be in uppercase. [1] 7

August_03 A1. (a) Briefly explain three differences between static and dynamic memory allocation. [6] static memory allocation - size is fixed at compilation time [1] - certain memory location is reserved [1] - cannot be created and destroyed during the execution of the program [1] dynamic memory allocation - not fixed during compilation time [1] - no memory location is reserved [1] - can be created and destroyed during the execution of the program [1] (b) List any two functions in the C language that are used in dynamic memory allocation. [2] Any two of the following, 1 mark each: malloc() [1] sizeof() [1] free() [1] calloc() [1] (c) Explain one disadvantage of using dynamic memory allocation. [2] Either of the following answers, up to max 2 marks for each: If you free a memory location which is still pointed by another pointer, [1] then further access to this location will either cause a run-time error or, you will get access to a location that is being used for some completely unrelated purpose. [1] If you forget to free up some unused memory spaces, then you are losing the advantages of dynamic allocation. [1] In some circumstances - e.g. if you were writing the program that manages the space on a disk drive, this could be disastrous. [1] 8

August_03 A4. (a) Explain what is meant by a pointer. [2] Pointer is a variable that references, or points to a storage location. [1] Its value is the address of a memory location. [1] (b) What is the special notation that is normally used for a pointer? [1] * [1] (c) Give a C statement showing how to define a pointer called np, which points to an integer. [1] int *np; [1] or typedef int *Intpoint; Intpoint np; [1] (d) Which unary operator returns the address of its operand? [1] August_03 & [1] B1. (c) List three ways in which a pointer s value can be changed [3] Method1: By assigning it to NULL, which gives it a null address e.g. First = NULL; [1] Method2: By assigning it with the address of another pointer of the same type. Both pointers will then point to the same location. e.g. First = Second; [1] Method3: Using the function malloc. This gives it a brand new address whose contents are undefined. e.g. First = (int *) malloc (sizeof(int)); [1] 9

April_03 A2. Consider the following two C language statements: Number = (int *) malloc (sizeof(int)); free (Number); Explain the terms below, as they are used in the examples: (a) Sizeof [2] (b) Malloc [2] (c) Free [2] (a) Sizeof Evaluates the number of bytes required for the data type integer. [2] (b) Malloc Dynamically allocates a portion of memory of an integer size and returns the address of this allocated location. [2] (c) Free frees the memory location that Number is pointing to and returns it to the heap. [2] April_03 A4 Consider the following diagrams, and state whether the statements which follow them are True or False. (a) The statement Q = P; copies into Q the value stored in P. [1] TRUE [1] 10

(b) *P and *Q are now two names for the same location. [1] TRUE [1] (c) *P and *Q now contain the same address: P == Q. [1] TRUE [1] (d) Consider this new situation: In this situation, the condition P == Q evaluates to true. [1] FALSE [1] (e) In this situation, the condition *P == *Q evaluates to true [1] TRUE [1] 11

April_03 A5. Briefly explain what is meant by indirect access and direct access. Give an example of each. [4] Indirect Access: Access the content of a location by using the middle man, pointers. [1] Direct Access: Access the content of a location by using a normal variable name. [1] e.g. [2 marks] int num=15, *ptr=&num; num=20; //direct access *ptr=100; //indirect access August_01 (NULL Pointer Vs Dangling pointer) A3 A3 Explain the main difference between a NULL pointer and a Dangling pointer. [ 2 marks] NULL pointer can be checked to see whether the pointer is pointing to a node or not, but a Dangling pointer cannot be checked. [ 2 marks] April_02(A3), August_01(A6) A3. Explain the meaning of each of the following terms: (a) Pointer [2] (a) A pointer is used to point /refer to a memory location [1] It stores the address of the memory location [1] August_02 (memory allocation) B1. (d) Assume there is a pointer ptr declared as follows: char *ptr; Using C built in functions as necessary, write a C statement to allocate sufficient memory for ptr. [2] ptr = (char *) malloc ( sizeof(char) ); [2] 12

August_00 (pointers) B2. (a) Given the following C pointer manipulation program, complete the statements that follow it by choosing the most appropriate answer from the list given. [7] #include <stdio.h> void main(void) { char a[ ] = "Good Day", *ptr, letter1 = 'Q', letter2 = 'T'; ptr = &letter1; printf("%c\n", *ptr); *ptr = letter2; printf("%c\n", *ptr); ptr = a; printf("%s\n", ptr); *ptr = a[5]; printf("%c", *ptr); } (i) The purpose of the statement ptr = &letter1 is to (a) Make the pointer ptr reference to the address of letter1. (b) Assign the value in letter1 to ptr. (c) Initialise the value of ptr to letter1. (ii) The output from the first printf statement is (a) Good Day (b) T (c) Q (iii) The output from the third printf statement is (a) T (b) Good Day (c) Q (iv) The purpose of the statement *ptr = letter2 is to (a) assign the address of letter2 to location referenced by ptr. (b) initialise the address in letter2 to location referenced by ptr. (c) assign the value in letter2 to location referenced by ptr. (v) The statement char a[ ] = Good Day is: (a) an initialisation (b) an assignment (c) not necessary (vi) The output from the fourth printf statement is (a) a space (b) D (c) a 13

(vii) The statement ptr = a is valid because (a) both the ptr and a holds address in memory location. (b) the size in ptr is equal to the size in a. (c) ptr only references an array. (i) a [1] (ii) c [1] (iii) b [1] (iv) c [1] (v) a [1] (vi) b [1] (vii) a [1] April_01 (static variable + pointers) B1. (b) Name two problems which can arise from the use of static data structures. [2] Overestimate of storage required [1] Underestimate of storage required [1] (c) Trace the program below and write down the output produced. [6] void main() { int *FirstPtr, *SecondPtr, *ThirdPtr; FirstPtr = (int *)malloc(sizeof(int)); SecondPtr = (int *)malloc(sizeof(int)); *FirstPtr = 10; *SecondPtr = 20; ThirdPtr = FirstPtr; printf("%d %d %d\n", *FirstPtr, *SecondPtr, *ThirdPtr); *ThirdPtr += *SecondPtr; printf("%d %d %d\n", *FirstPtr, *SecondPtr, *ThirdPtr); *SecondPtr = *ThirdPtr; *FirstPtr = *SecondPtr + 50; printf("%d %d %d\n", *FirstPtr, *SecondPtr, *ThirdPtr); } 10 20 10 [2] 30 20 30 [2] 80 30 80 [2] 14

August_01 (static variable) B1. (c) List four characteristics of a static variable. [ 4 marks] Size is fixed at compilation time [1] A certain memory location is reserved [1] Declared in a variable declaration section [1] Cannot be created or destroyed during program execution [1] April_02 (static variable) B1. (b) Give one disadvantage of using only static variables in a program. Explain two problems which might be encountered when using the following static array of data. int data[200]; [6] Disadvantage: The size of variables needed in a program must be predetermined. [2] Problems created: Overestimate the length of the array and part of the memory is wasted. [2] Underestimate the necessary array length and unable to process all the data unless the program is modified. [2] April_02 (memory allocation) B3. (c) Explain the purpose of the malloc( ) function in the C language. [1] The malloc( ) function in C is used for allocating memory dynamically. [1] 15

April_02 (pointer) B3. (f) List three ways in which a pointer s value can be changed and state briefly how these change are made, by providing C statements for each using the variables declared below. [6] int *P1, *P2; Method1: By assigning it to NULL, which gives it a null address [1] e.g. First = NULL; [1] Method2: By assigning it with the address of another pointer of the same type. Both pointers will then point to the same location. [1] e.g. First = Second; [1] Method3: Using the function malloc. This gives it a brand new address whose contents are undefined. [1] e.g. First = (int *) malloc (sizeof(int)); [1] August_02 (pointer + struct) B2. (a) Pointers are an important part of the C language. (i) Explain what is a pointer is. [2] (ii) Write a complete C program to show how to assign a value of 10 to a variable called qty (quantity) which is part of a structure called product. The structure is accessed through a pointer ptr, which must be declared. The structure contains 3 variables: _ prodid, product identification, a 10-character string _ qty, quantity of the product, an integer _ price, price of the product, a float [7] (i) A pointer is a variable that contains the address of another variable. [2] (ii) struct product { [1] char prodid[10]; [1] int qty; [1] float price; [1] } ; struct product *ptr; [1] void main() { [1] ptr ->qty = 10; [1] } 16