Programming in C. Lecture Tiina Niklander. Faculty of Science

Size: px
Start display at page:

Download "Programming in C. Lecture Tiina Niklander. Faculty of Science"

Transcription

1 Programming in C Lecture Tiina Niklander Faculty of Science Department of Computer Science

2 Week 2 covers Pointer basics operators and address arithmetics as function argument Precedence and associativity (covered in Lecture 2) Dynamic memory allocation Strings Linked lists Faculty of Science Department of Computer Science

3 Briefly about pointers char *p; /* pointer to a character or string */ int *q; /* pointer to one integer (or array) */ /*Memory allocated only for the pointer! */ 345 : Main memory Memory block char *p = This string is allocated ; int numbers[] = {1, 2, 3, 4, 5; double table[100]; Allocate memory for the array and map the name to address of the array. (No memory allocated for array name! constant pointer only allocates the memory block containing the values!) 678 : pointer p 680 : 915 : pointer q 740 : 830 : Program code function foo1 function foo2 Faculty of Science Department of Computer Science

4 Pointers (and arrays) Array is just a sequence of values with a joint name. int a[15] is sequence of 15 integers. Array name is treated as a pointer, whose value is the address of the first element in the sequence. pa = &a[0] pa = a pointer arithmetic allows operations on array elements *(pa +3) is the same as a[3] pa+3 is the same as &a[3] Faculty of Science Department of Computer Science

5 Pointer arithmetics and operations Remember: NULL p = &c c = *p c = **r p = q address of c value of the address pointed by p - - (two jumps ) allowed when p and q of same type p+i, p-i p is array, i has to be integer with suitable value p-q, p and q pointers of the same array and q<p p < q, p == q *ip++ increments the address by one (*ip)++ increments the value in the address by one Faculty of Science Department of Computer Science

6 Pointer arithmetics p int **p; int *q,*r; 3 i 12 int i; i = **p; q const int *p; q = &i; /* q s new value is i s address int const *p; i = *q+1; i = ++*q; /* i=6*/ const int const *p; i = *q++; /*???? */ r = q; *r = 3; /* i=3 */ char msg [] = It is time ; msg: It is time\0 char *pv = It is time ; It is time\0 void *p; i= *(int*) p; pv Faculty of Science Department of Computer Science

7 Example code int main(int argc, char** argv) { int x=1, y=2, z[10]; int *ip; int *p, q; int *r, *s; ip = &x; y = *ip; /* y = x =1 */ *ip = 0; /* x = 0 */ ip = &z[0]; p is a pointer variable and q is integer variable x y z ip double atof(char * string); Faculty of Science Department of Computer Science Pointers as arguments for functions are very common. (Always used with arrays and needed for call by reference)

8 Memory allocation Explicit memory allocations! malloc static data structures calloc dynamic array realloc change the size of already allocated object free deallocate the memory /* ALWAYS CHECK THE RETURN VALUE!!! */ if (!(k=malloc(sizeof(double)))) error; /* allocation failed, do something else or terminate program */ /* memory allocation succeeded and k is the pointer to the new structure */ Faculty of Science Department of Computer Science

9 Functions: Call by value, call by reference C uses always call by value => function cannot change the value it receives as argument. Call by reference done with pointers!!! void swap(int x, int y) { int apu; apu=x; x=y; y= apu; copies void swap(int *x, int *y) { int apu; apu=*x; *x=*y; *y= apu; Faculty of Science Department of Computer Science x y Addresses of x and y Call: swap (&x, &y); double product (const double block, int size); 3 4 Make sure that function does not change the variable (ANSI standard!)

10 #include <stdio.h> Example code: copy a string - Passing array to a function void copy_string( char *s, char *t) { int i =0; while ( (s[i] = t[i])!= \0 ) i++; Strings (character arrays ending with \0 ) as arguments. C is always passing only the address of the first element of any array. int main (void) Processing one character of each array { char here [] = This string is copied., there[50]; copy_string ( here, there); printf( %s\n, there); copy_string ( there, here); printf( %s\n, there); return 0; Faculty of Science Department of Computer Science

11 Example code: copy a string Now with pointers Version 1: Version 2: void copy_string( char *s, char *t) { while ( (*s = *t)!= \0 ) s++; t++; void copy_string( char *s, char *t) { while ( (*s++ = *t++)!= \0 ) ; Version 3: void copy_string( char *s, char *t) { while ( *s++ = *t++ ) ; NOTE: The function prototype is identical with the previous slide Faculty of Science Department of Computer Science Minimalistic!

12 More about pointers and some good practices Generic pointer (void *p) can be used with type cast to handle a variable of that type. *(double *)p Memory allocation for n integers int *p; if ((p=malloc(n*sizeof(int))) == NULL) error; Memory deallocation: remember to free(p); p=null; i th element of array p[i] (preferred over *(p+i) ) Handling an array p for (pi = p; pi < p+size; pi++) remember to use pointer pi in the loop Faculty of Science Department of Computer Science

13 Still more Call by reference 1. Prototype s argument a pointer void func(int *pp) 2. In the function use the pointed value. *pp 3. In the function call: address of the variable func(&variable); 4. In the function call: pointer func(pointer_variable); Array of struct (next slide) for (p = block; p < block + n*elsize; p+= elsize) i. element of struct array p = block + i*elsize Faculty of Science Department of Computer Science

14 Struct struct info { char firstname[20]; char lastname[20]; int age; ; struct info i1, i2; typedef struct InfoT { char firstname[20]; char lastname[20]; int age; InfoT; InfoT p1; Preferable alternative! Access to struct field with. notation struct.field: p1.age = 18; printf("%s\n", i2.firstname); struct info { char firstname[20]; char lastname[20]; int age; k1, k2;

15 Pointer to struct Access to struct field: (*p).x or p->x typedef struct pair { double x; double y; PairT, *PairTP; PairT x; PairTP p; PairT w; PairTP q; PairTP p = &w; if((q = malloc(sizeof(pairt))) == NULL) if((q = malloc(sizeof(struct pair))) == NULL) w.x = 2; p->x = 1; (*p).x = 1; *p.x = 1; q->y = 3.5;

16 Linked lists Faculty of Science Department of Computer Science

17 List (abstract data type) source: Wikipedia Sequential structure Access from the head (or tail) element by element Typical operations Creation Add element To beginning, to middle, to end Remove element From beginning, from middle, from end Locate first element Test for empty, Faculty of Science Department of Computer Science

18 List (abstract data type) List can be used to implement: Queue (FIFO, first-in-first-out) Enqueue to one end Dequeue from the other end Stack (LIFO, last-in-first-out) Push to top Pull from top Faculty of Science Department of Computer Science

19 List (abstract data type) List can be implemented Using array data structure Using linked list data structure Here focus only on the linked list data structure Faculty of Science Department of Computer Science

20 Linked lists List as abstract data structure: covered in data structures and algorithms course Linked list structural decisions: single or double (traversals to one or two directions) Loop or no-loop (= NULL terminated) Header node or not Ordered or not Unique elements or multiple occurrences of same value

21 Linked List - definitions Header, singly linked No loop = NULL to terminate NOTE: definition of the next field! typedef double DataType; typedef struct elem { DataType value; struct elem *next; ElemT, *ElemTP; typedef struct { ElemTP first; ListT, *ListTP; ListTP p; p first ListT value 2 next ElemT value 3.5 next NULL ElemT

22 Linked list with header: Create and delete Create list Just allocate header node and set its field values Delete list Separate function to remove elements Here just free space of header node ListTP construct(void) { ListTP p; if((p = malloc(sizeof(listt))) == NULL) return NULL; p->first = NULL; return p; void destruct(listtp *this) { clear(*this); /* remove list elements */ free(*this); *this = NULL;

23 Linked list with header: Using it All list operations must maintain the following invariants: For empty list, always p->first ==NULL. For non-empty list, always last node s next-field == NULL. p first ListT p NULL first ListT value 2 next ElemT value 3.5 next ElemT NULL

24 Linked list with header: using it p Operations: List traversal first ListT value 2 next ElemT Always (and only) to the link direction Adding to list Beginning, middle, end Removing from the list Beginning, middle, end value 3.5 next ElemT NULL

25 p List traversal first ListT value 2 next ElemT value 3.5 next ElemT aux void printall(const ListTP this) { ElemTP aux; for(aux=this->first; aux!=null; aux=aux->next) printf("%f\n", aux->value); NULL /* Keep aux in previous node */ If ((p->first!= NULL) && (p->first->next!=null)) for(aux = p->first; aux->next!= NULL; aux = aux->next)...

26 Add to beginning of the list p this first ListT int insertfront(listtp this, DataType d) { ElemTP aux; if((aux = malloc(sizeof(elemt))) == NULL) return 0; value 2 next ElemT value 2 next ElemT value 3.5 next ElemT aux NULL aux->next = this->first; /* save state */ aux->value = d; this->first = aux; return 1;

27 Removing last node int deletelast(listtp this, DataType *value) { ElemTP aux; if(this->first == NULL) /* empty list */ return 0; if(this->first->next == NULL) { /* single */ *value = this->first->value; free(this->first); this->first = NULL; return 1; for(aux = this->first; aux->next->next!= NULL; aux = aux->next) ; /* aux points to second last element */ *value = aux->next->value; free(aux->next); aux->next = NULL; return 1; p first ListT value 2 next ElemT value 3.5 next ElemT this aux NULL

28 Deleting/clearing the whole list Free node by node from beginning to end int deletefirst(listtp this) { ElemTP aux = this->first; if(aux == NULL) /* empty list */ return 0; this->first = aux->next; free(aux); return 1; void clear(listtp this) { while(deletefirst(this)) ; this->first = NULL; EXPLICIT MEMORY DEALLOCATION

29 Linked list without separate header node type No ListTP type, so only type is the ElemTP Pointer to list is pointer to the first element So empty list: pointer == NULL List changes Must pass to functions the address to the list pointer, value is not enough Faculty of Science Department of Computer Science

30 Example: ModuleList (doubly-linked list with header) Own module (list.h and list.c) that can be compiled separately, contains type definitions and functions This module can - Handle multiple separate lists - Data handled by void pointer, so different lists can contain different types of data - Hide the actual implementation details of the list Type definitions: ListItem and List Functions: CreateList, CreateItem, AddTail, AddHead, ListLength, DeleteList, PrintStringList, EmptyList Source: Jan Lindström s (Finnish) lecture material,2000

31 Interface definitions: list.h #ifndef MY_LIST_LIBRARY #define MY_LIST_LIBRARY /* Type definitions*/ typedef struct listitem { struct listitem *Next; /* Pointer to next element */ struct listitem *Prev; /* pointer to previous elem */ void *Data; /* Pointer to data */ unsigned long Size; /* Size of data */ ListItem; typedef struct { /* header node of the list */ ListItem *Head; ListItem *Tail; unsigned long Items; /* number of elements */ List;

32 List.h continues /* Function signatures / interface definitions*/ extern List *CreateList(void); /* Create new list */ extern ListItem *CreateItem(void *Data, unsigned long Size); /* Create new element*/ extern int AddTail(List *,ListItem *); /*Add to end*/ extern int AddHead(List *,ListItem *); /* Add to beginning */ extern unsigned long ListLength(List *); /* Count lenght */ extern void DeleteList(List *); /* Destroy list */ extern void PrintStringList(List *); /* Print the list content, assume strings */ extern int EmptyList(List *); /* Check if list is empty */ #endif

33 List.c : CreateList /* Reserve memory area for the new list and set the fields */ List *CreateList(void) { List *new; if(!(new = (List *)malloc(sizeof(list)))) return NULL; new->head = NULL; new->tail = NULL; new->items = 0; return new;

34 List.c: CreateItem /* Allocate memory for new node and set fields*/ ListItem *CreateItem(void *Data,unsigned long size) { ListItem *uusi; /* If no data, exit and do not create a node*/ if (Data == NULL) return NULL; if(!(uusi = (ListItem *)malloc(sizeof(listitem)))) return NULL; if(!(uusi->data = (void *)malloc(size))) return NULL; uusi->next = NULL; uusi->prev = NULL; memcpy(uusi->data,data,size); uusi->size = size; return uusi;

35 List.c: AddTail /* Add to the end of the list*/ extern int AddTail(List *lista,listitem *item) { if (lista == NULL item == NULL ) return 1; if ( lista->head == NULL) lista->head = lista->tail = item; else { lista->tail->next = item; item->prev = lista->tail; lista->tail = item; lista->items++; return 0;

36 List.c: AddHead /* Add to the head of the list*/ extern int AddHead(List *lista,listitem *item) { if (lista == NULL item == NULL ) return 1; if ( lista->head == NULL) lista->head = lista->tail = item; else { lista->head->prev = item; item->next = lista->head; lista->head = item; lista->items++; return 0;

37 List.c: ListLength ja EmptyList /* Count' list length */ unsigned long ListLength(List *lista) { if ( lista == NULL ) return 0; else return lista->items; /* Check if list is empty */ int EmptyList(List *lista) { if ( lista == NULL) return 1; else if (lista->head == NULL ) return 1; else

38 List.c:DeleteList /* Destroy the whole list*/ void DeleteList(List *lista) { ListItem *tmp; if ( lista == NULL ) return; tmp = lista->head; while(tmp!= NULL) { tmp = lista->head->next; free(lista->head->data); free(lista->head); lista->head = tmp; free(lista);

39 List.c: PrintStringList /* Print the whole list */ void PrintStringList(List *lista) { ListItem *tmp = lista->head; printf(" "); while(tmp!= NULL) { printf("%s ",(char *)tmp->data); tmp = tmp->next; printf(" -\n"); Here assumes that list contains strings. More generic solutions would be to use function parameter to handle data. Caller would then provide function to handle data elements and the print function would be more general.

Programming in C. Week Tiina Niklander. Faculty of Science

Programming in C. Week Tiina Niklander. Faculty of Science Programming in C Week2 15.9.2016 Tiina Niklander Faculty of Science Department of Computer Science 15.9.2016 1 Meeting structure First week Some notes Second week Focus on pointers Slides related to first

More information

Member Access through Pointer. The next lecture is on Tue, in Auditorio : Structures and Functions.

Member Access through Pointer. The next lecture is on Tue, in Auditorio : Structures and Functions. Member Access through Pointer The next lecture is on Tue, 26.11 in Auditorio 12-14 If p is a pointer to a structure that has a member w, then p->w gives access to w. Memory Allocation for a Structure For

More information

Kurt Schmidt. October 30, 2018

Kurt Schmidt. October 30, 2018 to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed

More information

Programming. Lists, Stacks, Queues

Programming. Lists, Stacks, Queues Programming Lists, Stacks, Queues Summary Linked lists Create and insert elements Iterate over all elements of the list Remove elements Doubly Linked Lists Circular Linked Lists Stacks Operations and implementation

More information

Linked List. April 2, 2007 Programming and Data Structure 1

Linked 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 information

malloc(), calloc(), realloc(), and free()

malloc(), calloc(), realloc(), and free() 1 next CITS2002 CITS2002 schedule Dynamic data structures Initially, we focused on scalar and array variables, whose size is known at compile-time. More recently, we've focused on arrays of values, whose

More information

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.

More information

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

A. 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 information

Programming in C Lecture 6

Programming in C Lecture 6 Programming in C Lecture 6 8.10.2018 Tiina Niklander Department of Computer Science www.cs.helsinki.fi 8.10.2018 1 Week 5 covers Macros Parameterized macros on this lecture Function pointers Void and void

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

Algorithms, Data Structures, and Problem Solving

Algorithms, Data Structures, and Problem Solving Algorithms, Data Structures, and Problem Solving Masoumeh Taromirad Hamlstad University DT4002, Fall 2016 Container Concepts containers store data container operations: insertion retrieval removal iteration

More information

Linked Lists in C and C++

Linked Lists in C and C++ Linked Lists in C and C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by

More information

Mid-term Exam. Fall Semester 2017 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID:

Mid-term Exam. Fall Semester 2017 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID: Fall Semester 2017 KAIST EE209 Programming Structures for Electrical Engineering Mid-term Exam Name: This exam is closed book and notes. Read the questions carefully and focus your answers on what has

More information

Dynamic 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 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 information

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty. ECE 264 Exam 2 6:30-7:30PM, March 9, 2011 I certify that I will not receive nor provide aid to any other student for this exam. Signature: You must sign here. Otherwise you will receive a 1-point penalty.

More information

Implementing an abstract datatype. Linked lists and queues

Implementing an abstract datatype. Linked lists and queues Computer Programming Implementing an abstract datatype. Linked lists and queues Marius Minea marius@cs.upt.ro 19 December 2016 Review: compilation basics Briefly: Compiler translates source code to executable

More information

Lecture 7: Data Structures. EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Lecture 7: Data Structures. EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology Lecture 7: Data Structures 1 Introduction: dynamic array Conventional array in C has fix number of elements Dynamic array is array with variable number of elements: actually a pointer and a variable indicating

More information

Dynamic memory allocation (malloc)

Dynamic 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 information

Programs in memory. The layout of memory is roughly:

Programs in memory. The layout of memory is roughly: Memory 1 Programs in memory 2 The layout of memory is roughly: Virtual memory means that memory is allocated in pages or segments, accessed as if adjacent - the platform looks after this, so your program

More information

Mid-term Exam. Fall Semester 2017 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID:

Mid-term Exam. Fall Semester 2017 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID: Fall Semester 2017 KAIST EE209 Programming Structures for Electrical Engineering Mid-term Exam Name: This exam is closed book and notes. Read the questions carefully and focus your answers on what has

More information

Lecture 3: C Programm

Lecture 3: C Programm 0 3 E CS 1 Lecture 3: C Programm ing Reading Quiz Note the intimidating red border! 2 A variable is: A. an area in memory that is reserved at run time to hold a value of particular type B. an area in memory

More information

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

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C Lecture 1 C primer What we will cover A crash course in the basics of C You should read the K&R C book for lots more details Various details will be exemplified later in the course Outline Overview comparison

More information

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

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides From Java to C Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides 1 Outline Overview comparison of C and Java Good evening Preprocessor

More information

Data Structures in C. C Programming and Software Tools. N.C. State Department of Computer Science

Data Structures in C. C Programming and Software Tools. N.C. State Department of Computer Science 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 allows for creation

More information

Cpt S 122 Data Structures. Data Structures

Cpt 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 information

Lecture 8 Dynamic Memory Allocation

Lecture 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 information

CP2 Revision. theme: dynamic datatypes & data structures

CP2 Revision. theme: dynamic datatypes & data structures CP2 Revision theme: dynamic datatypes & data structures structs can hold any combination of datatypes handled as single entity struct { }; ;

More information

Data Structures and Algorithms. Roberto Sebastiani

Data Structures and Algorithms. Roberto Sebastiani Data Structures and Algorithms Roberto Sebastiani roberto.sebastiani@disi.unitn.it http://www.disi.unitn.it/~rseba - Week 05 - B.S. In Applied Computer Science Free University of Bozen/Bolzano academic

More information

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

Cpt S 122 Data Structures. Course Review Midterm Exam # 1 Cpt S 122 Data Structures Course Review Midterm Exam # 1 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 1 When: Friday (09/28) 12:10-1pm Where:

More information

ESc101: (Linear, Circular, Doubly) Linked Lists, Stacks, Queues, Trees. Introduction to Linked Lists

ESc101: (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 information

Procedural programming with C

Procedural programming with C Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical

More information

Understanding Pointers

Understanding 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 information

Solution for Data Structure

Solution for Data Structure Solution for Data Structure May 2016 INDEX Q1 a 2-3 b 4 c. 4-6 d 7 Q2- a 8-12 b 12-14 Q3 a 15-18 b 18-22 Q4- a 22-35 B..N.A Q5 a 36-38 b N.A Q6- a 39-42 b 43 1 www.brainheaters.in Q1) Ans: (a) Define ADT

More information

Data Structures and Algorithms for Engineers

Data Structures and Algorithms for Engineers 04-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University

More information

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to. Pointers A pointer is a memory address of an object of a specified type, or it is a variable which keeps such an address. Pointer properties: P (pointer) 12316 12316 (address) Typed object A pointer value

More information

MODULE V: POINTERS & PREPROCESSORS

MODULE V: POINTERS & PREPROCESSORS MODULE V: POINTERS & PREPROCESSORS INTRODUCTION As you know, every variable is a memory-location and every memory-location has its address defined which can be accessed using ampersand(&) operator, which

More information

19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store)

19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store) Lecture 29 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 29: Linked Lists 19-Nov-2018 Location: Chemistry 125 Time: 12:35 13:25 Instructor: Vlado Keselj Previous

More information

Data Structure with C. List

Data Structure with C. List Subject: Data Structure with C Topic: List Introduction list is a finite sequence of data items, i.e. a collection of data items arranged in a certain linear order. he basic operations performed on this

More information

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

CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures CS113: Lecture 9 Topics: Dynamic Allocation Dynamic Data Structures 1 What s wrong with this? char *big_array( char fill ) { char a[1000]; int i; for( i = 0; i < 1000; i++ ) a[i] = fill; return a; void

More information

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36 Department of Computer Science College of Engineering Boise State University August 25, 2017 1/36 Pointers and Arrays A pointer is a variable that stores the address of another variable. Pointers are similar

More information

COP Programming Concepts Spring 1999 CLOSED BOOK Exam #1 100 Points NAME

COP Programming Concepts Spring 1999 CLOSED BOOK Exam #1 100 Points NAME CLOSED BOOK Exam #1 100 Points NAME 1. The following program has (at least) 10 syntax errors. Circle each error. Write the corrected program in the blank space below. 2 points for each error you find.

More information

Memory Allocation in C

Memory Allocation in C Memory Allocation in C When a C program is loaded into memory, it is organized into three areas of memory, called segments: the text segment, stack segment and heap segment. The text segment (also called

More information

So far, system calls have had easy syntax. Integer, character string, and structure arguments.

So far, system calls have had easy syntax. Integer, character string, and structure arguments. Pointers Page 1 So far, system calls have had easy syntax Wednesday, September 30, 2015 10:45 AM Integer, character string, and structure arguments. But this is not always true. Today, we begin to explore

More information

Department of Electrical and Computer Engineering The University of Texas at Austin

Department of Electrical and Computer Engineering The University of Texas at Austin Department of Electrical and Computer Engineering The University of Texas at Austin EE 312, Spring 2015 Aater Suleman, Instructor Owais Khan, Chirag Sakhuja, TAs Exam 1, March 4, 2015 Name: Problem 1 (20

More information

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

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine

More information

MODULE 5: Pointers, Preprocessor Directives and Data Structures

MODULE 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 information

Quick review pointer basics (KR ch )

Quick review pointer basics (KR ch ) 1 Plan for today Quick review pointer basics (KR ch5.1 5.5) Related questions in midterm Continue on pointers (KR 5.6 -- ) Array of pointers Command line arguments Dynamic memory allocation (malloc) 1

More information

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

Review: 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 information

Dynamic memory allocation

Dynamic 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 information

Introduction to Linked Lists

Introduction to Linked Lists Introduction to Linked Lists In your previous programming course, you organized and processed data items sequentially using an array (or possibly an arraylist, or a vector). You probably performed several

More information

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24 Memory Management a C view Dr Alun Moon Computer Science KF5010 Dr Alun Moon (Computer Science) Memory Management KF5010 1 / 24 The Von Neumann model Memory Architecture One continuous address space Program

More information

Lecture 2: C Programm

Lecture 2: C Programm 0 3 E CS 1 Lecture 2: C Programm ing C Programming Procedural thought process No built in object abstractions data separate from methods/functions Low memory overhead compared to Java No overhead of classes

More information

Ashish Gupta, Data JUET, Guna

Ashish Gupta, Data JUET, Guna Categories of data structures Data structures are categories in two classes 1. Linear data structure: - organized into sequential fashion - elements are attached one after another - easy to implement because

More information

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013 Linear Structure Linear Structures Chapter 4 CPTR 318 Every non-empty linear structure has A unique element called first A unique element called last Every element except last has a unique successor Every

More information

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings Lecture 4: Outline I. Pointers A. Accessing data objects using pointers B. Type casting with pointers C. Difference with Java references D. Pointer pitfalls E. Use case II. Arrays A. Representation in

More information

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

CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures CS113: Lecture 9 Topics: Dynamic Allocation Dynamic Data Structures 1 What s wrong with this? char *big_array( char fill ) { char a[1000]; int i; for( i = 0; i < 1000; i++ ) a[i] = fill; return a; void

More information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 6: Recursive Functions. C Pre-processor. Cristina Nita-Rotaru Lecture 6/ Fall 2013 1 Functions: extern and static Functions can be used before they are declared static for

More information

Advanced C Programming and Introduction to Data Structures

Advanced C Programming and Introduction to Data Structures FYBCA Semester II (Advanced C Programming and Introduction to Data Structures) Question Bank Multiple Choice Questions Unit-1 1. Which operator is used with a pointer to access the value of the variable

More information

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013 Linear Structure Linear Structures Chapter 4 CPTR 318 Every non-empty linear structure has A unique element called first A unique element called last Every element except last has a unique successor Every

More information

Overview of today s lecture. Quick recap of previous C lectures. Introduction to C programming, lecture 2. Abstract data type - Stack example

Overview of today s lecture. Quick recap of previous C lectures. Introduction to C programming, lecture 2. Abstract data type - Stack example Overview of today s lecture Introduction to C programming, lecture 2 -Dynamic data structures in C Quick recap of previous C lectures Abstract data type - Stack example Make Refresher: pointers Pointers

More information

CS24 Week 2 Lecture 1

CS24 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 information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 11: Structures and Memory (yaseminb@kth.se) Overview Overview Lecture 11: Structures and Memory Structures Continued Memory Allocation Lecture 11: Structures and Memory Structures Continued Memory

More information

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR STUDENT IDENTIFICATION NO MULTIMEDIA COLLEGE JALAN GURNEY KIRI 54100 KUALA LUMPUR FIFTH SEMESTER FINAL EXAMINATION, 2014/2015 SESSION PSD2023 ALGORITHM & DATA STRUCTURE DSEW-E-F-2/13 25 MAY 2015 9.00 AM

More information

CS61, Fall 2012 Section 2 Notes

CS61, 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 information

Common Misunderstandings from Exam 1 Material

Common Misunderstandings from Exam 1 Material Common Misunderstandings from Exam 1 Material Kyle Dewey Stack and Heap Allocation with Pointers char c = c ; char* p1 = malloc(sizeof(char)); char** p2 = &p1; Where is c allocated? Where is p1 itself

More information

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Pointers (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 information

Dynamic Memory Allocation

Dynamic Memory Allocation Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility, there are four library routines known as memory management

More information

Data Structures and Algorithms (DSA) Course 6 Lists (Recapitulation) Iulian Năstac

Data Structures and Algorithms (DSA) Course 6 Lists (Recapitulation) Iulian Năstac Data Structures and Algorithms (DSA) Course 6 Lists (Recapitulation) Iulian Năstac Recapitulation Operations related to a linked list: a) creation of a linked list; b) access to any node of the list; c)

More information

211: Computer Architecture Summer 2016

211: Computer Architecture Summer 2016 211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Structure: - header files - global / local variables - main() - macro Basic Units: - basic data types - arithmetic / logical / bit operators

More information

Computer Systems and Networks

Computer Systems and Networks University of the Pacific LECTURE 5: C PROGRAMMING Computer Systems and Networks Dr. Pallipuram (vpallipuramkrishnamani@pacific.edu) Today s Class o Pointer basics o Pointers and mul;- dimensional arrays

More information

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

C: 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 information

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C 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 information

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures

The 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 information

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS Contents Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS 1.1. INTRODUCTION TO COMPUTERS... 1 1.2. HISTORY OF C & C++... 3 1.3. DESIGN, DEVELOPMENT AND EXECUTION OF A PROGRAM... 3 1.4 TESTING OF PROGRAMS...

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 16. Linked Lists Prof. amr Goneid, AUC 1 Linked Lists Prof. amr Goneid, AUC 2 Linked Lists The Linked List Structure Some Linked List

More information

Dynamic Allocation of Memory

Dynamic Allocation of Memory Dynamic Allocation of Memory Lecture 5 Section 9.8 Robb T. Koether Hampden-Sydney College Wed, Jan 24, 2018 Robb T. Koether (Hampden-Sydney College) Dynamic Allocation of Memory Wed, Jan 24, 2018 1 / 34

More information

Data Structures and Algorithms for Engineers

Data Structures and Algorithms for Engineers 04-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University

More information

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive) Final Exam Exercises Chapters 1-7 + 11 Write C++ code to: l Determine if a number is odd or even CS 2308 Fall 2016 Jill Seaman l Determine if a number/character is in a range - 1 to 10 (inclusive) - between

More information

Structures. 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. 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 information

Linked Data Representations

Linked 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 information

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables) Memory Allocation Memory What is memory? Storage for variables, data, code etc. How is memory organized? Text (Code) Data (Constants) BSS (Global and static variables) Text Data BSS Heap Stack (Local variables)

More information

Programming in C Lecture Tiina Niklander

Programming in C Lecture Tiina Niklander Programming in C Lecture 5 1.10.2018 Tiina Niklander Liisa Marttinen & Tiina Niklander www.cs.helsinki.fi C programming 2016 1 Week 4 covers Multidimensional arrays Pointer arrays Command-line arguments

More information

Linked Data Representations. Data Structures and Programming Techniques

Linked Data Representations. Data Structures and Programming Techniques Linked Data Representations 1 Linked Data Representations Linked data representations such as lists, stacks, queues, sets and trees are very useful in Computer Science and applications. E.g., in Databases,

More information

Dynamic Data Structures. CSCI 112: Programming in C

Dynamic Data Structures. CSCI 112: Programming in C Dynamic Data Structures CSCI 112: Programming in C 1 It s all about flexibility In the programs we ve made so far, the compiler knows at compile time exactly how much memory to allocate for each variable

More information

Darshan Institute of Engineering & Technology for Diploma studies Unit 4

Darshan 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 information

BBM 201 DATA STRUCTURES

BBM 201 DATA STRUCTURES BBM 201 DATA STRUCTURES Lecture 8: Dynamically Allocated Linked Lists 2017-2018 Fall int x; x = 8; int A[4]; An array is stored as one contiguous block of memory. How can we add a fifth element to the

More information

Data Structures and Algorithms (DSA) Course 5 Lists. Iulian Năstac

Data 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 information

Lectures 5-6: Introduction to C

Lectures 5-6: Introduction to C Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most

More information

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Pointers Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) Pointers February 29, 2012 1

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #54. Organizing Code in multiple files

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #54. Organizing Code in multiple files Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #54 Organizing Code in multiple files (Refer Slide Time: 00:09) In this lecture, let us look at one particular

More information

Linked List using a Sentinel

Linked List using a Sentinel Linked List using a Sentinel Linked List.h / Linked List.h Using a sentinel for search Created by Enoch Hwang on 2/1/10. Copyright 2010 La Sierra University. All rights reserved. / #include

More information

ENEE150 Final Exam Review

ENEE150 Final Exam Review ENEE150 Final Exam Review Topics: Pointers -- pointer definitions & initialization -- call-by-reference and Call-by-value -- pointer with arrays -- NULL pointer, void pointer, and pointer to pointer Strings

More information

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco CS 326 Operating Systems C Programming Greg Benson Department of Computer Science University of San Francisco Why C? Fast (good optimizing compilers) Not too high-level (Java, Python, Lisp) Not too low-level

More information

EL6483: Brief Overview of C Programming Language

EL6483: Brief Overview of C Programming Language EL6483: Brief Overview of C Programming Language EL6483 Spring 2016 EL6483 EL6483: Brief Overview of C Programming Language Spring 2016 1 / 30 Preprocessor macros, Syntax for comments Macro definitions

More information

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto Ricardo Rocha Department of Computer Science Faculty of Sciences University of Porto Adapted from the slides Revisões sobre Programação em C, Sérgio Crisóstomo Compilation #include int main()

More information

ECE 15B COMPUTER ORGANIZATION

ECE 15B COMPUTER ORGANIZATION ECE 15B COMPUTER ORGANIZATION Lecture 13 Strings, Lists & Stacks Announcements HW #3 Due next Friday, May 15 at 5:00 PM in HFH Project #2 Due May 29 at 5:00 PM Project #3 Assigned next Thursday, May 19

More information

PROGRAMMAZIONE I A.A. 2017/2018

PROGRAMMAZIONE I A.A. 2017/2018 PROGRAMMAZIONE I A.A. 2017/2018 LINKED LISTS LINKED LIST What are the problems with arrays? üsize is fixed üarray items are stored contiguously üinsertions and deletions at particular positions is complex

More information

Data Structures and Algorithms for Engineers

Data Structures and Algorithms for Engineers 04-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University

More information

Final CSE 131B Spring 2004

Final CSE 131B Spring 2004 Login name Signature Name Student ID Final CSE 131B Spring 2004 Page 1 Page 2 Page 3 Page 4 Page 5 Page 6 Page 7 Page 8 (25 points) (24 points) (32 points) (24 points) (28 points) (26 points) (22 points)

More information