Programming in C Pointer Basics.

Slides:



Advertisements
Similar presentations
C Language.
Advertisements

C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
1 Chapter Thirteen Pointers. 2 Pointers A pointer is a sign used to point out the direction.
Kernighan/Ritchie: Kelley/Pohl:
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Pointers| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2006 Slide 1 Pointers by Jumail Bin Taliba Faculty of Computer.
Programming in C Pointer Basics.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Programming in C Advanced Pointers. Pointers to Pointers Since a pointer is a variable type, a pointer may point to another pointer.Since a pointer is.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Welcome to Concepts of Pointers. Prepared by:- Sumit Kumar PGT(Computer Science) Kv,Samba.
POINTERS.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
POINTERS IN C Pointer Basics, Pointer Arithmetic, Pointer to arrays and Pointer in functions.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
CSC 215 Pointers and Arrays. Pointers C provides two unary operators, & and *, for manipulating data using pointers The operator &, when applied to a.
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
Lecture 5 Pointers 1. Variable, memory location, address, value
C Structures and Memory Allocation
Dynamic Storage Allocation
CS1010 Programming Methodology
EGR 2261 Unit 11 Pointers and Dynamic Variables
Pointers and Dynamic Arrays
Computer Organization and Design Pointers, Arrays and Strings in C
User-Written Functions
Structures, Unions, Enumerations
UNIT 5 C Pointers.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 9: Pointers.
Learning Objectives Pointers Pointer in function call
Pointers Revisited What is variable address, name, value?
C Basics.
Pointer.
Lecture 6 C++ Programming
Pointers and References
Dynamic Memory Allocation
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Lecture 9 Structure 1. Concepts of structure Pointers of structures
Programming in C Pointer Basics.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers and Dynamic Variables
Chapter 9: Pointers.
Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes
CMSC202 Computer Science II for Majors Lecture 04 – Pointers
Pointers, Dynamic Data, and Reference Types
Pointers Problem Solving & Program Design in C Eighth Edition
Programming in C Pointer Basics.
Pointers and Dynamic Variables
Programming in C Pointer Basics.
C++ Pointers and Strings
Pointers Pointers point to memory locations
Chapter 9: Pointers and String
Module 9 Pointers.
C Structures and Memory Allocation
Programming in C Advanced Pointers.
C++ Pointers and Strings
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

Programming in C Pointer Basics

Java Reference In Java, the name of an object is a reference to that object. Here ford is a reference to a Truck object. It contains the memory address at which the Truck object is stored. Truck ford = new Truck( ); The syntax for using the reference is pretty simple. Just use the “dot” notation. ford.start( ); ford.drive( 23 ); ford.turnLeft( );

What is a pointer ? In C, a pointer variable (or just “pointer”) is similar to a reference in Java except that A pointer can contain the memory address of any variable type (Java references only refer to objects) A primitive (int, char, float) An array A struct or union Dynamically allocated memory Another pointer A function There’s a lot of syntax required to create and use pointers 1/14/10

Why Pointers? They allow you to refer to large data structures in a compact way They facilitate sharing between different parts of programs They make it possible to get new memory dynamically as your program is running They make it easy to represent relationships among data items. 1/14/10

Pointer Caution They are a powerful low-level device. Undisciplined use can be confusing and thus the source of subtle, hard-to-find bugs. Program crashes Memory leaks Unpredictable results 1/14/10

C Pointer Variables To declare a pointer variable, we must do two things Use the “*” (star) character to indicate that the variable being defined is a pointer type. Indicate the type of variable to which the pointer will point (the pointee). This is necessary because C provides operations on pointers (e.g., *, ++, etc) whose meaning depends on the type of the pointee. General declaration of a pointer type *nameOfPointer; 1/14/10

Pointer Declaration The declaration int *intPtr; defines the variable intPtr to be a pointer to a variable of type int. intPtr will contain the memory address of some int variable or int array. Read this declaration as “intPtr is a pointer to an int”, or equivalently “*intPtr is an int” Caution -- Be careful when defining multiple variables on the same line. In this definition int *intPtr, intPtr2; intPtr is a pointer to an int, but intPtr2 is not! 1/14/10

Pointer Operators The two primary operators used with pointers are * (star) and & (ampersand) The * operator is used to define pointer variables and to dereference a pointer. “Dereferencing” a pointer means to use the value of the pointee. The & operator gives the address of a variable. Recall the use of & in scanf( ) 1/14/10

Pointer Code Use ampersand ( & ) to obtain the address of the pointee Use star ( * ) to get / change the value of the pointee Use %p to print the value of a pointer with printf( ) What is the output from this code? See pointer1.c int a = 1, *ptr1; /* show value and address of a ** and value of the pointer */ ptr1 = &a ; printf("a = %d, &a = %p, ptr1 = %p, *ptr1 = %d\n", a, &a, ptr1, *ptr1) ; /* change the value of a by dereferencing ptr1 ** then print again */ *ptr1 = 35 ; printf(“a = %d, &a = %p, ptr1 = %p, *ptr1 = %d\n", a, &a, ptr1, *ptr1) ; 1/14/10

Pointer Examples 1/14/10 int x = 1, y = 2, z[10] = {0}; int *ip; // ip is a “pointer to an int” // but doesn’t point to anything yet ip = &x; // now ip points to (contains the memory address of) x y = *ip; // has the same effect as .... *ip = 0; // has the same effect as .... *ip = *ip + 10; // has the same effect as ..... ip = &y; // now ip points to a different int printf( “%d”, *ip); // has the same effect as .... scanf(“%d”, ip); // has the same effect as .... ip = &z[4]; // now ip points toanother different int - z[4] *ip = x + y; // has the same effect as .... 1/14/10

Pointer and Variable types The type of a pointer and its pointee must match int a = 42; int *ip; double d = 6.34; double *dp; ip = &a; /* ok -- types match */ dp = &d; /* ok */ ip = &d; /* compiler error -- type mismatch */ dp = &a; /* compiler error */ 1/14/10

NULL NULL is a special value which may be assigned to a pointer NULL indicates that this pointer does not point to any variable (there is no pointee) Often used when pointers are declared int *pInt = NULL; Often used as the return type of functions that return a pointer to indicate function failure int *myPtr; myPtr = myFunction( ); if (myPtr == NULL){ /* something bad happened */ } Dereferencing a pointer whose value is NULL will result in program termination. 1/14/10

Pointers and Function Arguments Since C passes all primitive function arguments “by value” there is no direct way for a function to alter a variable in the calling code. /* version 1 of swap */ void swap (int a, int b) { int temp; temp = a; a = b; b = temp; } /* calling swap from somewhere in main() */ int x = 42, y = 17; swap( x, y ); printf(“%d, %d\n”, x, y); // what does this print? Trace the execution of swap to show that this doesn’t work 1/14/10

A better swap( ) The desired effect can be obtained by passing pointers to the values to be exchanged. This is a very common use of pointers. /* pointer version of swap */ void swap (int *px, int *py) { int temp; temp = *px; *px = *py; *py = temp; } /* calling swap from somewhere in main( ) */ int x = 42, y = 17; swap( &x, &y ); printf(“%d, %d\n”, x, y); // what does this print? Trace the execution of swap showing how/where variables are changed 1/14/10

More Pointer Function Parameters Passing the address of variable(s) to a function can be used to have a function “return” multiple values. The pointer arguments point to variables in the calling code which are changed (“returned”) by the function. Akin to “pass by reference”, but with syntax required within the function. 1/14/10

convertTime.c static void convertTime (int time, int *pHours, int *pMins) { *pHours = time / 60; *pMins = time % 60; } int main( ) int time, hours, minutes; printf("Enter a time duration in minutes: "); scanf ("%d", &time); convertTime (time, &hours, &minutes); printf("HH:MM format: %02d:%02d\n", hours, minutes); return 0; 1/14/10

An Exercise What is the output from this code? static void myFunction (int a, int *b) { a = 7 ; *b = a ; b = &a ; *b = 4 ; printf("%d, %d\n", a, *b) ; } int main() int m = 3, n = 5; myFunction(m, &n) ; printf("%d, %d\n", m, n) ; return 0; 1/14/10

Pointers to struct /* define a struct for related student data */ typedef struct student { char name[50]; char major [20]; double gpa; } STUDENT; STUDENT bob = {"Bob Smith", "Math", 3.77}; STUDENT sally = {"Sally", "CSEE", 4.0}; STUDENT *pStudent; /* pStudent is a "pointer to struct student" */ /* make pStudent point to bob */ pStudent = &bob; /* use -> to access the members */ printf ("Bob's name: %s\n", pStudent->name); printf ("Bob's gpa : %f\n", pStudent->gpa); /* make pStudent point to sally */ pStudent = &sally; printf ("Sally's name: %s\n", pStudent->name); printf ("Sally's gpa: %f\n", pStudent->gpa); Note too that the following are equivalent. Why?? pStudent->gpa and (*pStudent).gpa /* the parentheses are necessary */ See pointer2Struct.c 1/14/10

Pointer to struct for functions void printStudent(STUDENT *studentp) { printf(“Name : %s\n”, studentp->name); printf(“Major: %s\n”, studentp->major); printf(“GPA : %4.2f”, studentp->gpa); } Passing a pointer to a struct to a function is more efficient than passing the struct itself. Why is this true? 9/24/10