Programming in C. Pointers and Arrays

Similar documents
CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

POINTER AND ARRAY SUNU WIBIRAMA

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING PREVIEW SLIDES 14, SPRING 2013

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 14, FALL 2012

Arrays, Strings, & Pointers

Procedures, Parameters, Values and Variables. Steven R. Bagley

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

Lesson #8. Structures Linked Lists Command Line Arguments

Introduction to Computer Science Midterm 3 Fall, Points

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

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

Arrays and Pointers in C. Alan L. Cox

Pointers and scanf() Steven R. Bagley

Introduction to Computing Systems Fall Lab # 3

CMSC 212 Midterm #2 (Fall 2005) ANSWERS AND GRADING KEY

Intermediate Programming, Spring 2017*

ECE264 Fall 2013 Exam 1, September 24, 2013

EL2310 Scientific Programming LAB2: C lab session. Patric Jensfelt, Andrzej Pronobis

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

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 14

CS 108 Computing Fundamentals. October/November Array Bootcamp

EE 312 Fall 2018 Midterm 1 Version A October 10, 2018

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

Hello, World! in C. Johann Myrkraverk Oskarsson October 23, The Quintessential Example Program 1. I Printing Text 2. II The Main Function 3

EE 312 Fall 2017 Midterm 1 October 12, 2017

Array Initialization

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

CS2141 Software Development using C/C++ C++ Basics

Binghamton University. CS-211 Fall Pointers

Kurt Schmidt. October 30, 2018

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

C Language: Review. INFO High Performance Scientific Computing. 26 septembre 2017

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

PRINCIPLES OF OPERATING SYSTEMS

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

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

CS-211 Fall 2017 Test 1 Version A Oct. 2, Name:

Course organization. Course introduction ( Week 1)

NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313.

Number Review. Lecture #3 More C intro, C Strings, Arrays, & Malloc Variables. Clarification about counting down

CSE101-Lec#17. Arrays. (Arrays and Functions) Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

COMP 2355 Introduction to Systems Programming

CSE 333 Lecture 2 Memory

Character Strings. String-copy Example

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

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

Week 7 Part I. Kyle Dewey. Monday, August 6, 12

CS 220: Introduction to Parallel Computing. Input/Output. Lecture 7

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

Midterm Exam Nov 8th, COMS W3157 Advanced Programming Columbia University Fall Instructor: Jae Woo Lee.

CSE 124 Discussion (10/3) C/C++ Basics

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

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

PROGRAMMAZIONE I A.A. 2017/2018

Strings. Steven R. Bagley

COMP 111 PROGRAMMING I MODULARITY USING FUNCTIONS

Chapter 6 - Pointers

ECE264 Spring 2013 Final Exam, April 30, 2013

Arrays and Pointers. CSE 2031 Fall November 11, 2013

FUNCTIONS POINTERS. Pointers. Functions

COMP2521. Generic ADTs in C

Variables, Pointers, and Arrays

CSCI565 Compiler Design

Pointers. Pointers. Pointers (cont) CS 217

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

HW1 due Monday by 9:30am Assignment online, submission details to come

Data Representation and Storage

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

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

ECE264 Spring 2013 Exam 1, February 14, 2013

unsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

#include <stdio.h> int main() { char s[] = Hsjodi, *p; for (p = s + 5; p >= s; p--) --*p; puts(s); return 0;

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

Intermediate Programming, Spring 2017*

We do not teach programming

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

Arrays, Pointers and Memory Management

Data Representation and Storage. Some definitions (in C)

Introduction to C An overview of the programming language C, syntax, data types and input/output

Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays

C programming basics T3-1 -

CS 376b Computer Vision

CS 0449 Sample Midterm

COMP 2355 Introduction to Systems Programming

Common Misunderstandings from Exam 1 Material

Lecture 05 POINTERS 1

Today s Learning Objectives

CMSC 202. Pointers Dynamic Memory Allocation

Goals of this Lecture

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Lecture 04 Introduction to pointers

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

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

Transcription:

Programming in C Pointers and Arrays

NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313 http://www.csee.umbc.edu/courses/undergraduate/313/fall11/"

Pointers and Arrays In C, there is a strong relationship between pointers and arrays. The declaration int a[10]; defines an array of 10 integers. The declaration int *p; defines p as a pointer to an int. The assignment p = a; makes p an alias for the array and sets p to point to the first element of the array. (We could also write p = &a[0];) We can now reference members of the array using either a or p a[4] =9; p[3] = 7; int x = p[6] + a[4] * 2; 1/14/10 2

More Pointers and Arrays The name of an array is equivalent to a pointer to the first element of the array and vice-versa. Therefore, if a is the name of an array, the expression a[ i ] is equivalent to *(a + i). It follows then that &a[ i ] and (a + i) are also equivalent. Both represent the address of the i-th element beyond a. On the other hand, if p is a pointer, then it may be used with a subscript as if it were the name of an array. p[ i ] is identical to *(p + i) In short, an array-and-index expression is equivalent to a pointer-and-offset expression and vice-versa. 1/14/10 3

So, what s the difference? If the name of an array is synonymous with a pointer to the first element of the array, then what s the difference between an array name and a pointer? An array name can only point to the first element of its array. It can never point to anything else. A pointer may be changed to point to any variable or array of the appropriate type 1/14/10 4

Array Name vs Pointer int g, grades[ ] = {10, 20, 30, 40 }, mygrade = 100, yourgrade = 85, *pgrade; /* grades can be (and usually is) used as array name */ for (g = 0; g < 4; g++) printf( %d\n grades[g]); /* grades can be used as a pointer to its array if it doesn t change*/ for (g = 0; g < 4; g++) printf( %d\n *(grades + g); /* but grades can t point anywhere else */ grades = &mygrade; /* compiler error */ /* pgrades can be an alias for grades and used like an array name */ pgrades = grades; /* or pgrades = &grades[0]; */ for( g = 0; g < 4; g++) printf( %d\n, pgrades[g]); /* pgrades can be an alias for grades and be used like a pointer that changes */ for (g = 0; g < 4; g++) printf( %d\n *pgrades++); /* BUT, pgrades can point to something else other than the grades array */ pgrades = &mygrade; printf( %d\n, *pgrades); pgrades = &yourgrade; printf( %d\n, *pgrades); 7/28/09 5

More Pointers & Arrays If p points to a particular element of an array, then p + 1 points to the next element of the array and p + n points n elements after p. The meaning a adding 1 to a pointer is that p + 1 points to the next element in the array, REGARDLESS of the type of the array. 1/14/10 6

Pointer Arithmetic If p is an alias for an array of ints, then p[ k ] is the k-th int and so is *(p + k). If p is an alias for an array of doubles, then p[ k ] is the k-th double and so is *(p + k). Adding a constant, k, to a pointer (or array name) actually adds k * sizeof(pointer type) to the value of the pointer. This is one important reason why the type of a pointer must be specified when it s defined. 7/28/09 7

Pointer Gotcha But what if p isn t the alias of an array? Consider this code. int a = 42; int *p = &a; printf( %d\n, *p); // prints 42 ++p; // to what does p point now? printf( %d\n, *p); // what gets printed? 7/28/09 8

Printing an Array The code below shows how to use a parameter array name as a pointer. Although this is not common and is more complex than need be, it illustrates the important relationship between pointers and array names. { } void printgrades( int grades[ ], int size ) int i; for (i = 0; i < size; i++) printf( %d\n, *grades ); ++grades; What about this prototype? void printgrades( int *grades, int size ); 1/14/10 9

Passing Arrays Arrays are passed by reference. When an array is passed to a function, the address of the array is copied onto the function parameter. Since an array address is a pointer, the function parameter may be declared in either fashion. E. g. int sumarray( int a[ ], int size) is equivalent to int sumarray( int *a, int size) The code in the function is free to use a as an array name or as a pointer as it sees fit. The compiler always sees a as a pointer. In fact, any error messages produced will refer to a as an int * 7/28/09 10

sumarray int sumarray( int a[ ], int size) { } int k, sum = 0; for (k = 0; k < size; k++) sum += a[ k ]; return sum; 7/28/09 11

sumarray (2) int sumarray( int a[ ], int size) { int k, sum = 0; for (k = 0; k < size; k++) sum += *(a + k); return sum; } int sumarray( int a[ ], int size) { int k, sum = 0; for (k = 0; k < size; k++) } sum += *a; ++a; } return sum; } 7/28/09 12

Strings revisited Recall that a string is represented as an array of characters terminated with a null (\0) character. As we ve seen, arrays and pointers are closely related. A string constant may be declared as either as in char[ ] or char* char hello[ ] = Hello Bobby ; or (almost) equivalently char *hi = Hello Bob ; A typedef could also be used to simplify coding typedef char* STRING; STRING hi = Hello Bob ; 7/28/09 13

Arrays of Pointers Since a pointer is a variable type, we can create an array of pointers just like we can create any array of any other type. Although the pointers may point to any type, the most common use of an array of pointers is an array of char* to create an array of strings. 7/28/09 14

Boy s Names A common use of an array of pointers is to create an array of strings. The declaration below creates an initialized array of strings (char *) for some boys names. The diagram below illustrates the memory configuration. char *name[] = { Bobby, Jim, Harold }; names: 0 1 2 B o b b y \0 J i m \0 H a r o l d \0 7/28/09 15

Command Line Arguments Command line arguments are passed to your program as parameters to main. int main( int argc, char *argv[ ] ) argc is the number of command line arguments (and hence the size of argv) argv is an array of strings which are the command line arguments. Note that argv[0] is always the name of your executable program. For example, typing myprog hello world 42 at the linux prompt results in argc = 4 argv[0] = myprog argv[1] = hello argv[2] = world argv[3] = 42 Note that to use argv[3] as an integer, you must convert if from a string to an int using the library function atoi( ). E.g. int age = atoi( argv[3] ); 7/28/09 16