Pointers. Addresses in Memory Everything in memory has an address. C allows us to obtain the address that a variable is stored at. scanf() is an example.

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
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.
Programming and Data Structure
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Pointers in C Rohit Khokher
BBS514 Structured Programming (Yapısal Programlama)1 Pointers.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Copyright 2004 Scott/Jones Publishing Starting Out with C++: Early.
Pointers Ethan Cerami Fundamentals of Computer New York University.
Pointers A pointer is a variable that contains memory address as its value. A variable directly contains a specific value. A pointer contains an address.
Even More C Programming Pointers. Names and Addresses every variable has a location in memory. This memory location is uniquely determined by a memory.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 14P. 1Winter Quarter Pointers Lecture 14.
Computer Science 210 Computer Organization Pointers.
Pointers CSE 2451 Rong Shi.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 14P. 1Winter Quarter Pointers Lecture 14.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
POINTERS. 1.a) POINTER EXPRESSIONS Pointer variables can be used in expression If p1 and p2 are properly declared and initialized pointers then following.
Chapter 9 Pointers Fall 2005 Csc 125 Introduction to C++
Pointers Chapter 9. Getting The Address Of A Variable Each variable in program is stored at a unique address Use address operator & to get address of.
Chapter 7: Pointers Basic concept of pointers Pointer declaration Pointer operator (& and *) Parameter passing by reference.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 6 (Pointers) © CPCS
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Spring 2005, Gülcihan Özdemir Dağ Lecture 6, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 6 Outline 6.1Introduction.
Review 1 List Data Structure List operations List Implementation Array Linked List.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 7: Pointers.
C Programming - Structures. Structures containing arrays A structure member that is an array does not ‘behave’ like an ordinary array When copying a structure.
Pointers *, &, array similarities, functions, sizeof.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
+ Pointers. + Content Address of operator (&) Pointers Pointers and array.
Arrays, Part 2 We have already learned how to work with arrays using subscript notation. Example: float myData[] = {3.5, 4.0, 9.34}; myData[0] += 2; printf("myData[0]
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman CP 202 Chapter 6.
Pointers PART - 2. Pointers Pointers are variables that contain memory addresses as their values. A variable name directly references a value. A pointer.
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;
2/23/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 9 (C-3)
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.
POINTERS IN C Pointer Basics, Pointer Arithmetic, Pointer to arrays and Pointer in functions.
Array of pointers We can have an array whose members are pointers, in this example pointers-to-int. int* data[3]; int i; int x = 5; int y = 89; int z =
Pointers. Addresses in Memory Everything in memory has an address. C allows us to obtain the address that a variable is stored at. scanf() is an example.
POINTER Dong-Chul Kim BioMeCIS UTA 3/13/
Functions and Pointers Dr. Sajib Datta Oct 6, 2014.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
CSE 251 Dr. Charles B. Owen Programming in C1 Pointers and Reference parameters.
Lecture 9 - Pointers 1. Outline Introduction Pointer Variable Definitions and Initialization Pointer Operators Calling Functions by Reference Pointer.
Pointers A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
Pointers Pointers are variables that contain memory addresses as their values. A variable directly contains a specific value. A pointer contains an address.
Pointers. Pointer Arithmetic Since arrays consist of contiguous memory locations, we can increment (or decrement) the addresses to move through the array.
Lecture 5 Pointers 1. Variable, memory location, address, value
Chapter 8 Arrays, Strings and Pointers
Computer Science 210 Computer Organization
CSE 220 – C Programming Pointers.
UNIT 5 C Pointers.
Functions and Pointers
Standard Version of Starting Out with C++, 4th Edition
Pointers.
INC 161 , CPE 100 Computer Programming
Pointers.
Functions and Pointers
Computer Science 210 Computer Organization
Pointers.
CSE1320 Strings Dr. Sajib Datta
CSE1320 Strings Dr. Sajib Datta
Pointers.
Standard Version of Starting Out with C++, 4th Edition
Presentation transcript:

Pointers

Addresses in Memory Everything in memory has an address. C allows us to obtain the address that a variable is stored at. scanf() is an example using the address of a variable ▫scanf("%d", &year);

Addresses in Memory Preceding a variable name by an ampersand, known as the address operator, will return its address: #include int main(void) { int x; /* notice the format specifier in printf() for an address is %p */ printf("The address for the memory allocated to x is %p\n", &x); return 0; }

hexadecimal (or called base-16) ABCDEF The address for the memory allocated to x is 0012FF60 in the previous example. For 32 bits system the 0012FF60 hexadecimal will be converted to 32 bits binary (one hex character represented by 4 bits).

Pointer A pointer is a variable whose value is a memory address. Note the type of a pointer indicates the type of variable which it points to. ▫E.g., int * (called pointer-to-int type) should be initialized to point to a variable of type int. ▫Similarly, we have char*, float *, …… Given a pointer variable, assignment can be done by using: ▫int * ptr = &pooh; /*assigns pooh’s address to ptr, we say ptr points to pooh*/ ▫ptr = &bah; /*make ptr point to some other variables*/

#include int main(void) { int num = 3, num1 = 5; int* numptr; /* numptr is a pointer */ printf("content of num is %d\n", num); printf("address of num is %p\n", &num); printf("address of num1 is %p\n", &num1); numptr = &num; /* initialize numptr with the address of num */ printf("content of numptr is %p\n", numptr); numptr = &num1; printf("content of numptr is %p\n", numptr); return 0; }

#include int main(void) { int num = 3, num1 = 5; int* numptr; /* numptr is a pointer */ printf("content of num is %d\n", num); printf("address of num is %p\n", &num); printf("address of num1 is %p\n", &num1); numptr = &num; /* initialize numptr with the address of num */ printf("content of numptr is %p\n", numptr); numptr = &num1; printf("content of numptr is %p\n", numptr); return 0; } Output: content of num is 3 address of num is 0012FF60 address of num1 is 0012FF54 content of numptr is 0012FF60 content of numptr is 0012FF54 Press any key to continue...

Why pointers C was developed when computers were much less powerful The raw ability to work with particular memory locations was obviously a useful option to have. Programming microcontrollers still need this. Optimize a program to run faster or use less memory that it would otherwise.

#include int main(void) { int arr[3] = {2, 4, 6}, i; for(i = 0; i<3; i++) printf("The address of %d element is %p.\n", i, &arr[i]); return 0; } The address of 0 element is 0032FE08. The address of 1 element is 0032FE0C. The address of 2 element is 0032FE10.

Indirection operator Pointers allow us to modify content in memory by using indirection operator (or called dereference operator). Putting an asterisk before your pointer variable See the example in the next slide

What’s going here? #include int main(void) { int bah = 10, val; int* ptr = &bah; val = *ptr; printf("The value of val is %d.\n", val); return 0; }

Pointers We can use pointers in much the same way we do the variables that they point to. #include int main(void) { int a = 3, b = 3; /* a and b start with equal values */ int* bptr = &b; /* we’ll modify b using a pointer */ a *= 4; *bptr *= 4; printf("a is %d, b is %d\n", a, b); a--; (*bptr)--; /* parentheses are necessary here to override the order of precedence */ printf("a is %d, b is %d\n", a, b); return 0; }

Output: a is 12, b is 12 a is 11, b is 11

Define multiple pointers together Wrong! If you use int * a, b to define two integer pointer variables. Instead, you should use int * a, *b; #include int main(void) { int * a, *b;//it’s wrong if int *a,b int c = 10; b = &c; a = &c; printf("b: %p and a: %p\n", b, a); return 0; }

Pointers to Pointers Pointers can contain the address of another pointer. int main(void) { int num = 5; int* numptr = &num; int** ptr2 = &numptr; /* notice the two asterisks */ printf("num is %d\n", num); printf("*numptr is %d\n", *numptr); printf("The content in numptr is %p.\n", numptr); printf("*ptr2 is %p\n", *ptr2); printf("**ptr2 is %d\n", **ptr2); return 0; }

Output num is 5 *numptr is 5 The content in numptr is 0012FF60 *ptr2 is 0012FF60 **ptr2 is 5

Comparing Pointers Note the difference between comparing the contents of pointers and the variables that pointers point to. To compare the addresses stored in pointers, use ▫if(numptr == valptr) To compare the values of the variables that pointers point to, use ▫if(*numptr == *valptr)

Pointers and Functions Previously, we made function calls like this: ▫int x = 3; ▫int y; ▫y = do_something(x); In this case, a copy of the variable’s value are passed to the function in a process called pass by value.

Pointers and Functions Passing pointers to a function will allow us to change the value of the original variable, called pass by reference, We do this by passing the variable’s address to the function. We already know passing array to a function is pass by reference. What’s the association between array and pointer?????

Pointers and Functions #include void interchange(int * u, int * v); int main(void) { int x = 5, y = 10; printf("Originally x = %d and y = %d.\n", x,y); interchange(&x, &y); printf("Now x = %d and y = %d.\n", x,y); return 0; } void interchange(int * u, int * v) { int temp; temp = *u; *u = *v; *v = temp; }

Pointers and Functions #include void tripleNum(int* aptr); int main(void) { int num = 8; int* numptr = &num; printf("before the function call, num is %d\n", num); tripleNum(numptr); /*or simply use &num*/ printf("after the function call, num is %d\n", num); } void tripleNum(int* aptr) /* pass by reference */ { *aptr = 3 * *aptr; /* first asterisk is for multiplication, second is to dereference the pointer */ }

Array review We have already learned how to work with arrays using subscript notation. Example: ▫float myData[] = {3.5, 4.0, 9.34}; ▫myData[0] += 2; ▫printf("myData[0] is %f\n", myData[0]);

Pointers and Arrays The array name evaluates to the address of the first element in the array. int data[] = {5, 6, 7}; int* dataptr = data; /* notice that we don’t use the ampersand here */ int* firstptr = &data[0]; /* we use & here since data[0] evaluates to a number */ printf("*dataptr is %d, *firstptr is %d\n", *dataptr, *firstptr);

Pointer Arithmetic Since arrays consist of contiguous memory locations, we can increment (or decrement) the addresses to move through the array. int data[] = {5, 6, 7}; int i; for (i = 0; i < 3; i++) printf("the value at address %p is %d\n", (data + i), *(data + i));

Pointer Arithmetic We can use pointer arithmetic with pointers to non-array ▫int data[] = {5, 6, 7}; ▫int* dataptr = data; ▫printf("pointer address = %p, next address = %p\n", dataptr, dataptr + 1);

Pointer Arithmetic #include int main(void) { char chararray[] = {68, 97, 114, 105, 110}; /* 1 byte each */ int intarray[] = {10, 11, 12, 13, 14}; /* 4 bytes each */ int i; printf("chararray intarray\n"); printf(" \n"); for(i = 0; i < 5; i++) printf("%p, %p\n", (chararray + i), (intarray + i)); return 0; }

chararray intarray FF58, 0012FF3C 0012FF59, 0012FF FF5A, 0012FF FF5B, 0012FF FF5C, 0012FF4C Press any key to continue...

Array of pointers We can have an array whose members are pointers, in this example pointers-to-int. int* data[3]; int i; int x = 5; int y = 89; int z = 34; data[0] = &x; data[1] = &y; data[2] = &z; for(i = 0; i < 3; i++) printf("%d\n", *data[i]);

#include int main() { printf("The address of the string is %p.\n", "apple"); printf("The length of the string is %d.\n", strlen("Hello")); return 0; } Output: The address of the string is The length of the string is 5. Press any key to continue...

References for pointers

String functions strcat() strcpy() strtok()

strcat() strcat() for string concatenation Take two strings for arguments A copy of the second string is tacked onto the end of the first, and this combined version becomes the new first string. The second string is not altered. The return type of strcat () is char *, the value of its first argument – the address of the first character of the string to which the second string is appended.

Strcat() cont. #include int main(void) { char flower[80]; char addon[] = " is a cat."; scanf("%s", flower); strcat(flower, addon); printf("%s\n",flower); return 0; } Note!!! strcat( ) not checking whether the first array is large enough to hold the second string.

If your input is Kitty, your output is going to be as follow. Kitty is a cat.

Strcpy() #include int main(void) { char orig[] = "beast"; char copy[80] = "Be the best that you can be."; strcpy(copy, orig); printf("copy - %s\n", copy); printf(“orig - %s\n", orig); return 0; }

Strcpy() #include int main(void) { char orig[] = "beast"; char copy[80] = "Be the best that you can be."; strcpy(copy+7, orig); printf("copy - %s\n", copy); printf(“orig - %s\n", orig); return 0; }

Output copy - Be the beast orig - beast