Pointers Chapters 6+9 in ABC. abp 12 int a = 1, b = 2, *p; & - reference operator (address) * - dereference operator (value) p = &a; // *p is now 1 abp.

Slides:



Advertisements
Similar presentations
Linked Lists CSE 2451 Matt Boggus. Dynamic memory reminder Allocate memory during run-time malloc() and calloc() – return a void pointer to memory or.
Advertisements

Data Structure Lecture-5
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 20 Arrays and Strings
1 Lecture13: Other C Topics 12/17/2012. Topics Variable-length argument lists Pointers to functions Command-line arguments Suffixes for integer and floating-point.
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
More Pointers Write a program that: –Calls a function to input an integer value –The above function calls another function that will double the input value.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8.
8 주 강의 Arrays, Pointers, and Strings. One dimensional array int grad0, grad1, grad2;  int grad[3]; int a[size]; /* a[0], …, a[size-1] #define N 100 int.
Kernighan/Ritchie: Kelley/Pohl:
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Pointers Discussion 5 Section Housekeeping HW 1 Issues Array Issues Exam 1 Questions? Submitting on Time!
Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A2 – Pointers (Revision)
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.
Structures and Lists (and maybe stacks) Chapters 9-10.
Arrays, Pointers and Strings Chapter 6 in ABC. One Dimensional Arrays #defineN100 int a[N]; for ( i = 0; i< N; ++i ) sum += a[i]; space for a[0],...,
CS61C L4 C Pointers (1) Chae, Summer 2008 © UCB Albert Chae Instructor inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 –C Strings,
Lecture 25 Self-Referential Structures Linked Lists
CPT: Arrays of Pointers/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to illustrate the use of arrays.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Chapter 9 Pointers Fall 2005 Csc 125 Introduction to C++
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Lecture 13 Static vs Dynamic Memory Allocation
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
CPT: Strings/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to discuss strings and their relationship.
14/3/02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Structures, ADT Lecture 25 14/3/2002.
C Programming Lecture 10-1 : Array & Pointer. Character Array String A sequence of characters The last character should be ‘\0’ that indicates “the end.
Structures. Heterogeneous Structures Collection of values of possibly different types. Name the collection. Name the components. Example : Student record.
Department of Computer Engineering Faculty of Engineering, Prince of Songkla University 1 3 – Pointers.
Weeks 5-6 Pointers and Arrays Basic pointer type Pointers and Arrays Address arithmetic Pointer Arrays User-defined data types Structures Unions Pointers.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
More Pointers and Arrays Kernighan/Ritchie: Kelley/Pohl: Chapter 5 Chapter 6.
Arrays and Pointers.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 5.
Arrays, Strings, and Memory. Command Line Arguments #include int main(int argc, char *argv[]) { int i; printf("Arg# Contents\n"); for (i = 0; i < argc;
Advanced Pointer Topics. Pointers to Pointers u A pointer variable is a variable that takes some memory address as its value. Therefore, you can have.
Pointers1 WHAT IS A POINTER? Simply stated, a pointer is an address. A running program consists of three parts: execution stack, code, and data. They are.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
Sudeshna Sarkar, CSE, IIT Kharagpur1 Structure and list processing Lecture
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
19-Feb-02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Arrays, Pointers, Strings Lecture 18 19/2/2002.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
Pointers. Pointer Fundamentals  When a variable is defined the compiler (linker/loader actually) allocates a real memory address for the variable. –int.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
Pointers (Revision). 2 Overview Revision of Pointers Pointers and structs Basic Pointer Arithmetic Pointers and Arrays.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Generic Programming in C
Dynamic Allocation Review Structure and list processing
2016.
Pointers Department of Computer Science-BGU יום שלישי 31 יולי 2018.
Some examples.
Pointers.
Pointers.
C Programming Language
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
Pointers.
Pointers.
prepared by Senem Kumova Metin modified by İlker Korkmaz
Outline Defining and using Pointers Operations on pointers
C++ Pointers and Strings
(PART 2) prepared by Senem Kumova Metin modified by İlker Korkmaz
Arrays, Pointers, and Strings
Structures EECS July 2019.
C++ Pointers and Strings
Pointers.
Presentation transcript:

Pointers Chapters 6+9 in ABC

abp 12 int a = 1, b = 2, *p; & - reference operator (address) * - dereference operator (value) p = &a; // *p is now 1 abp 12 Pointers

Why are they important? Call by reference Efficient argument passing to functions Dynamic memory allocation Efficient memory manipulation

Call by reference #include void swap(int *p, int *q) { int tmp; tmp = *p; *p = *q; *q = tmp; } int main(void) { int i = 3, j = 5; swap(&i, &j); printf( “%d %d\n”, i, j ); return 0; } Define pointers as params Use dereferenced values Pass addresses as arguments

Arrays and Pointers a[i] is equivalent to *(a + i) p[i] is equivalent to *(p + i) for ( p = a; p < &a[ N ]; ++p ) sum += *p; is equivalent to: for ( i = 0; i < N; ++i ) sum += a[i]; An array name is an address! The main difference between the two: a pointer can be modified, an array cannot, it is a CONSTANT pointer!

Pointer Arithmetic and Element Size double a[2], *p = NULL, *q = NULL; p = a; q = p +1; printf(“%d\n”, q - p); printf(“%d\n”, (int)q - (int)p); points to the base of the array equivalent to q = &a[ 1 ] 1 is printed sizeof(dobule)==8 is printed

Passing an array to a function double sum(double a[], int n) { int i = 0; double sum = 0.0; for ( i = 0; i < n; ++i ) sum += a[i]; return sum; } What will sum(a+3, 3) compute? Base address is passed call by value.

Strings char s[] = “abcde” s abcde\0 #include char *strcat(char *s1, const char *s2); int strcmp(const char *s1, const char *s2); char *strcpy(char *s1, const char *s2); unsigned strlen(const char *s);

An implementation example char *strcat( char *s1, const char *s2 ) { register char *p = s1; while ( *p ) ++p; while ( *p++ = *s2++ ) ; return s1; }

Dynamic memory allocation #include Functions work with void * - a generic pointer; all return NULL on failure size_t is typically unsigned int void *calloc( size_t n, size_t el_size) //all allocated bytes are initialized to zero void *malloc( size_t size ) //no initialization void free( void *ptr )

Lexicographical sort (lexi-sort.c) int main(void) { char *w[N]; char word[MAXWORD]; int n = 0, i = 0; for ( i = 0; scanf("%s", word) == 1; ++i ) { if ( i >= N ) { printf( “Sorry, at most %d words can be sorted.”, N ); exit(1); } w[i] = calloc(strlen(word) + 1, sizeof(char)); assert(w[i]!=NULL); strcpy(w[i], word); } an array of pointers work space Check allocation

Lexicographical sort n = i; sort_words( w, n ); for ( i = 0; i < n; ++i ) printf( “%s\n”, w[i] ); return 0; } print the sorted words

void sort_words( char *w[], int n ) { int i = 0, j = 0; for ( i = 0; i < n; ++i ) for ( j = i + 1; j < n; ++j ) if ( strcmp(w[i], w[j]) > 0 ) swap( &w[i], &w[j] ); } void swap( char **p, char **q ) { char *temp = NULL; temp = *p; *p = *q; *q = temp; } Lexicographical sort n elements to be sorted

Arguments to main() (echo.c) #include void main(int argc, char *argv[]) { int i = 0; printf( “argc = %d\n”, argc ); for ( i = 0; i < argc; ++i ) printf( “argv[%d] = %s\n”, i, argv[i] ); }

Multidimensional Arrays int a[5][2]={{1,2},{3,4},{5,6},{7,8},{9,10}}; a[i][j] is equivalent to *(&a[0][0]+2*i+j) What is **(a+3) ? What is *(a[2]+1) ?

Functions as arguments double sum_square( double f(double), int m, int n ) { int k = 0; double sum = 0.0; for ( k = m; k <= n; ++k ) sum += f(k) * f(k); return sum; } double sum_square( double (*f)(double), int m, int n ) {.....

Functions as arguments #include double f(double), sin(double), sum_square(double (*)(double), int, int); int main(void) { printf( “%s%.7f\n%s%.7f\n”, “ First computation: ”, sum_square(sin, 2, 13), “Second computation: ”, sum_square(f, 1, 10000)); return 0; } double f(double x) { return 1.0 / x; First computation: } Second computation:

The qsort function (int-qsort.c) qsort's prototype in stdlib.h: void qsort(void *array, size_t n_elem, size_t elem_size, int compare(const void *, const void *)); compare(a,b) returns negative int if a<b returns 0 if a=b returns positive int if a>b

// qsort an array of ints #include #define KEYSIZE 16 int compare_int(const void *p1, const void *p2); void print_array(char *title, int *key, int n_elem); int main(void) { int key[] = { 4, 3, 1, 67, 55, 8, 0, 4, -5, 37, 7, 4, 2, 9, 1, -1 }; print_array("before ", key, KEYSIZE); qsort(key, KEYSIZE, sizeof(int), compare_int); print_array("after ", key, KEYSIZE); return 0; }

void print_array(char *title, int *key, int n_elem) { int i; printf("\n %s:\n",title); for (i = 0; i < n_elem; ++i) printf("%4d", key[i]); putchar('\n'); } // the compare function to be passed as a parameter to qosrt int compare_int(const void *p1, const void *p2) { const int *q1 = p1, *q2 = p2; return ((*q1) - (*q2)); }

Linked lists typedef struct list { int data; struct list * next; } ll; void insert( ll *p, int a ) { //assume p!=NULL struct list *q = p->next; p->next = (ll *)malloc( sizeof( ll ) ); assert(p->next != NULL); p->next->data = a; p->next->next = q; } datanext

Linked lists void remove( ll *p ) { //assume p,p->next != NULL ll *q = p->next; p->next = q->next; free( q ); }

LINKED #include typedef char DATA; struct linked_list { DATA d; struct linked_list *next; }; typedef struct linked_listELEMENT; typedef ELEMENT *LINK; We will use chars in the example

Iterative List Creation LINK string_to_list( char s[] ) { int i = 0; LINK head = NULL, tail = NULL; if ( s[0] != ‘\0’ ) { head = ( ELEMENT* )malloc( sizeof( ELEMENT ) ); head→d = s[0]; tail = head; String is not empty

for ( i=1; s[i] != ‘\0’; ++i ) { tail→next = ( ELEMENT* )malloc( sizeof( ELEMENT ) ); tail = tail→next; tail→d = s[i]; } tail→next = NULL; } return head; } insert elements at the end of the list mark the end of the list

List deletion (recursive) void delete_list (LINK head) { if( head!= NULL ) { delete_list( head->next ); free( head ); } Free only after using the pointer