Binghamton University. CS-220 Spring Arrays in C

Similar documents
C Arrays and Pointers

Binghamton University. CS-211 Fall Pointers vs. Arrays

ONE DIMENSIONAL ARRAYS

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

Array Initialization

Binghamton University. CS-211 Fall Pointers vs. Arrays

C strings. (Reek, Ch. 9) 1 CS 3090: Safety Critical Programming in C

Coursework 2: Basic Programming

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

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

Characters, Character Strings, and string-manipulation functions in C

CS 449 Lecture 3. Variables in memory. Dr. Jack Lange. int x = 4;

C for Engineers and Scientists: An Interpretive Approach. Chapter 10: Arrays

Lesson 7. Reading and Writing a.k.a. Input and Output

Week 5. Muhao Chen.

How to declare an array in C?

QUIZ: loops. Write a program that prints the integers from -7 to 15 (inclusive) using: for loop while loop do...while loop

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

CS 33. Introduction to C. Part 5. CS33 Intro to Computer Systems V 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

EM108 Software Development for Engineers

Strings. Part III. 1) Introduction. 2) Definition. 3) Using Strings. 4) Input/Output. 5) Using string.h Library. 6) Strings as Function Parameters

Strings. Arrays of characters. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY

Create a Program in C (Last Class)

Binghamton University. CS-211 Fall Pointers

upper and lower case English letters: A-Z and a-z digits: 0-9 common punctuation symbols special non-printing characters: e.g newline and space.

STRUCTURED DATA TYPE ARRAYS IN C++ ONE-DIMENSIONAL ARRAY TWO-DIMENSIONAL ARRAY

Computers Programming Course 10. Iulian Năstac

Review! * follows a pointer to its value! & gets the address of a variable! Pearce, Summer 2010 UCB! ! int x = 1000; Pearce, Summer 2010 UCB!

CS61C : Machine Structures

Chapter 16. Pointers and Arrays. Address vs. Value. Another Need for Addresses

Array. Prepared By - Rifat Shahriyar

Pointers, Arrays, and Strings. CS449 Spring 2016

Computer Programming: Skills & Concepts (CP) Strings

Computers Programming Course 11. Iulian Năstac

Pointers. Memory. void foo() { }//return

Arrays and Pointers (part 1)

Arrays and Pointers in C. Alan L. Cox

ECE 15B COMPUTER ORGANIZATION

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

C Programming Language Review and Dissection III

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

CS-220 Spring 2018 Test 1 Version A Feb. 28, Name:

For example, let s say we define an array of char of size six:

Personal SE. Functions, Arrays, Strings & Command Line Arguments

Computer Systems Programming. Practice Midterm. Name:

Assignment 1 Clarifications

Character Strings. String-copy Example

String constants. /* Demo: string constant */ #include <stdio.h> int main() {

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Arrays and Pointers (part 1)

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

Single Dimension Arrays

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

FOR Loop. FOR Loop has three parts:initialization,condition,increment. Syntax. for(initialization;condition;increment){ body;

Procedural Programming & Fundamentals of Programming

Week 7: Pointers and Arrays. BJ Furman 02OCT2009

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Introduction to Programming Block Tutorial C/C++

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

Using Character Arrays. What is a String? Using Character Arrays. Using Strings Life is simpler with strings. #include <stdio.

CS1100 Introduction to Programming

Exercise 1.1 Hello world

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14

Data Types and Computer Storage Arrays and Pointers. K&R, chapter 5

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

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

Overview. Concepts this lecture String constants Null-terminated array representation String library <strlib.h> String initializers Arrays of strings

More Arrays. Last updated 2/6/19

More C Pointer Dangers

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING

Grade Distribution. Exam 1 Exam 2. Exams 1 & 2. # of Students. Total: 17. Total: 17. Total: 17

Arrays. Defining arrays, declaration and initialization of arrays. Designed by Parul Khurana, LIECA.

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

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

ESC101N: Fundamentals of Computing End-sem st semester

Chapter 10. Arrays and Strings

Week 8: Arrays and File I/O. BJ Furman 21OCT2009

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

Object oriented programming C++

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

CS 137 Part 6. ASCII, Characters, Strings and Unicode. November 3rd, 2017

CSE 230 Intermediate Programming in C and C++ Arrays and Pointers

Slide Set 3. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

Work relative to other classes

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

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

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

EE 312 Fall 2017 Midterm 1 October 12, 2017

Arrays and Strings. Arash Rafiey. September 12, 2017

This is CS50. Harvard University Fall Quiz 0 Answer Key

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

Intermediate Programming, Spring 2017*

C programming language continued: Recursion, strings and pointer

Data Types. Data Types. Introduction. Data Types. Data Types. Data Types. Introduction

The output: The address of i is 0xbf85416c. The address of main is 0x80483e4. arrays.c. 1 #include <stdio.h> 3 int main(int argc, char **argv) 4 {

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

PROGRAMMAZIONE I A.A. 2017/2018

Computer Organization & Systems Exam I Example Questions

Transcription:

Arrays in C 1

One Dimensional Array (Vector) Ordered List of Values All of the same type Individual elements accessible by index Vector has a Size (Number of elements) 0 1 2 3 4 5 17.3 14.5 3.2 12.0 5.65 14.5 2

One Dimensional Array Declaration type name[size]; type - Any built-in or derived data type int, char, short, float, etc. name - Any valid variable name e.g. vx, vy, myarray, etc. etc. size - Integer constant - how many items are in the list WARNING: Indeces are 0,1,2,3,, (size-1)! Vectors must be declared before they are used. 3

Referencing Vector Values name[index] name - The (declared) name of a vector index - The index of a specific element in the vector First element in the vector is vec[0] Last element in the vector is vec[size-1] Index may be any valid integer expression e.g. : vec[3], vec[j], vec[2*i+1] 4

Example Vector Code int grades[14]; // Code with fills in grades goes here int j,sum=0; for(j=0; j<14; j++) { sum +=grades[j]; } float avg=(float)sum/14; printf( Average grade: %f\n,avg); 5

Initializing a Vector int x=7; // Initializing a scalar variable int gpc[12]={4,4,6,4,3,3,2,2,3,1,4,4}; // Initializing vector 0 1 2 3 4 5 6 7 8 9 10 11 4 4 6 4 3 3 2 2 3 1 4 4 Or, let the compiler count the number of elements int gpc[ ]= {4,4,6,4,3,3,2,2,3,1,4,4}; IF ARRAY IS NOT INITIALIZED IT S INITIAL VALUE IS UNKNOWN! 6

Matrix Two Dimensional Array Declaration: type name[rows][cols]; Reference: name[row_index][col_index] 0 <= row_index < rows 0 <= col_index < cols Indexes may be any integer expressions 7

Array Dimensions Matrix: int matrix[2][3]={10,11,12,20,21,22} Vector: int vec[4]={10,20,30,40}; vec[0] vec[1] vec[2] vec[3] 10 20 30 40 matrix[0][0] 10 matrix[1][0] 20 matrix[0][1] 11 matrix[1][1] 21 matrix[0][2] 12 matrix[1][2] 22 Cube: char cube[3][2][3] = { abcdefghijklmnopqr }; [2][0][0] m [2][0][1] n [2][0][2] o [1][0][0] g [1][0][1] h [1][0][2] i [2][1][0] p [2][1][1] q [2][1][2] r [0][0][0] a [0][0][1] b [0][0][2] c [1][1][0] j [1][1][1] k [1][1][2] l [0][1][0] d [0][1][1] e [0][1][2] f 8

Array Values are Contiguous Right next to each other in memory int vec[6] int m [4][3]; vec[0] vec[1] vec[2] vec[3] vec[4] vec[5] m[0][0] m[0][1] m[0][2] m[1][0] m[1][1] m[1][2] m[2][0] m[2][1] m[2][2] m[3][0] m[3][1] m[3][2] 9

Row Major Order Think of multi-dimensional indexes as an odometer Rightmost digit of index increases the fastest Once rightmost digit reaches it s limit, it goes back to zero, and Digit to the left increases by 1 int m[4][3]={0,1,2,10,11,12, 20,21,22,30,31,32}; 0 1 2 0 0 1 2 1 10 11 12 2 20 21 22 3 30 31 32 m[0][0] m[0][1] m[0][2] m[1][0] m[1][1] m[1][2] m[2][0] m[2][1] m[2][2] m[3][0] m[3][1] m[3][2] 0 1 2 10 11 12 20 21 22 30 31 32 10

Array Bounds Checking vec[0] 4 int vec[5]; int i; for(i=0;i<=5;i++) vec[i]=4; vec[1] 4 vec[2] 4 vec[3] 4 vec[4] 4 i 4 NO RUN-TIME ARRAY BOUNDS CHECKING IN C!!!!!!!!!!!! Trust the programmer, and save the run-time! Programmer must be trustworthy! Writing past the end of an array can cause many problems May write over other variables May cause a segmentation violation 11

Strings in C 12

What is a string? A string is just a vector of ASCII characters Followed by a null terminator a byte with the value 0x00 char str[14]= This a string ; { T, h, i, s,, a,, s, t, r, i, n, g, x00} Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 ASCII T h i s a s t r i n g Hex x54 x68 x69 x73 x20 x61 x20 x73 x74 x72 x69 x6e x67 x00 13

The null terminator A null terminator is a single byte with the value 0b00000000 A null terminator is NOT a null address not NULL! 0x0000000000000000 A null terminator is NOT an integer 0 0x000000000 When we assign a word 0 to a char 0, the left bits are truncated So we can assign 0 to a char to get a null terminator When we compare a null-terminator to a word 0, the null terminator is extended to word length So we can compare a byte to 0 to see if it is a null terminator To avoid confusion, I use 0x00 as a null terminator (0b00000000) You will also see \0 the ASCII escaped null terminator (0b00000000)

printf substitutes a string for %s char str[14]= This a string ; printf( Variable str contains: %s : and no more\n,str); Variable str contains: This a string : and no more 15

Empty String char str[14]= This a string ; str[0]=x00; printf( Variable str contains: %s : and no more\n,str); Variable str contains: : and no more Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 ASCII h i s a s t r i n g Hex x00 x68 x69 x73 x20 x61 x20 x73 x74 x72 x69 x6e x67 x00 16

Standard Library String Functions #include <string.h> char str[18]= This a string ; printf( Size of str buffer: %d\n,sizeof(str)); printf( Length of str string: %d\n,strlen(str)); Size of str buffer: 18 Length of str string: 13 Indx 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 char T h i s a s t r i n g Hex x54 x68 x69 x73 x20 x61 x20 x73 x74 x72 x69 x6e x67 x00 x00 x00 x00 x00 17

strlen(char str[ ]); Returns the number of bytes up to (but not including) the null terminator of the argument string. Because we start indexes at zero: str[strlen(str)]==x00 // ALWAYS TRUE! char empty[20]= ; printf( Length of empty: %d\n,strlen(empty)); Length of empty: 0 18

strcpy(char to[ ],char from[ ]) Copies from string to to string ASSUMES to is large enough to hold strlen(from) char buf[100]= Old string ; char new[20]= Newer string ; strcpy(buf,new); printf( Variable buf contains: %s : and no more\n,buf); Variable buf contains: Newer string : and no more 19

strcat(char start[ ],char tail[ ]) Copies tail string at the end of start string ASSUMES start is large enough to hold both start and tail char start[100]= Beginning ; char end[20]= of a test. ; strcat(start,end); printf( Variable start contains: %s : and no more\n,start); Variable start contains: Beginning of a test. : and no more 20

strncat(char start[ ],char tail[ ],int n) Copies up to n bytes of tail string at the end of start string ASSUMES start is big enough to hold both start and n bytes of tail Safer than strcat char start[100]= Beginning ; char end[20]= of a test. ; strncat(start,end,6); printf( Variable start contains: %s : and no more\n,start); Variable start contains: Beginning of a t : and no more 21

strcmp(char a[ ], char b[ ]) Compares the string in a to the string in b If a<b, returns a number less than zero If a==b, returns zero If a>b, returns a number greater than zero Cannot compare strings with ==, <, >, <=, etc. operators! Can compare CHARACTERS with ==, <, if (0==strcmp(name, Tom )) printf( Hi Tom ); 22

strncmp(char a[], char b[],int n) Compares the string in a to the string in b for up to n characters If a<b, returns a number less than zero If a==b, returns zero If a>b, returns a number greater than zero Cannot compare strings with ==, <, >, <=, etc. operators! Can compare CHARACTERS with ==, <, if (0==strncmp(name, Tom,3)) printf( Name starts with Tom ); 23

Resources The C Programming Language, (K&R) Section 1.6 (Arrays), 1.9 (strings) Wikipedia C String Handling https://en.wikipedia.org/wiki/c_string_handling C String Tutorial : http://www.tutorialspoint.com/cprogramming/c_strings.htm 24