Arrays in C C Programming and Software Tools. N.C. State Department of Computer Science

Similar documents
Memory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Functions in C C Programming and Software Tools

More about BOOLEAN issues

CSC 1600 Memory Layout for Unix Processes"

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

Vector and Free Store (Pointers and Memory Allocation)

CS61C : Machine Structures

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

CS61C : Machine Structures

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

How to declare an array in C?

Arrays and Pointers. CSE 2031 Fall November 11, 2013

For instance, we can declare an array of five ints like this: int numbers[5];

At this time we have all the pieces necessary to allocate memory for an array dynamically. Following our example, we allocate N integers as follows:

Module 6: Array in C

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

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.

Types II. Hwansoo Han

Arrays and Pointers in C & C++

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

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

APS105. Collecting Elements 10/20/2013. Declaring an Array in C. How to collect elements of the same type? Arrays. General form: Example:

CS61C : Machine Structures

Hacking in C. Pointers. Radboud University, Nijmegen, The Netherlands. Spring 2019

Chapter 17 vector and Free Store

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Data Types. Data Types. Integer Types. Signed Integers

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

Language comparison. C has pointers. Java has references. C++ has pointers and references

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

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

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

Procedural Programming & Fundamentals of Programming

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

ECE 15B COMPUTER ORGANIZATION

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

More C Pointer Dangers

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

o Code, executable, and process o Main memory vs. virtual memory

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

CS61C : Machine Structures

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

Array Initialization

printf( Please enter another number: ); scanf( %d, &num2);

CSE / ENGR 142 Programming I

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II:

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

a) Write the signed (two s complement) binary number in decimal: b) Write the unsigned binary number in hexadecimal:

[0569] p 0318 garbage

Fundamentals of Programming

CSC 252: Computer Organization Spring 2018: Lecture 9

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

Variables and literals

Outline Arrays Examples of array usage Passing arrays to functions 2D arrays Strings Searching arrays Next Time. C Arrays.

Reminder: compiling & linking

Pointers and References

Intermediate Programming, Spring 2017*

Reference slides! Garcia, Fall 2011 UCB! CS61C L04 Introduction to C (pt 2) (1)!

Chapter 17 vector and Free Store. Bjarne Stroustrup

Lecture 5: Outline. I. Multi- dimensional arrays II. Multi- level arrays III. Structures IV. Data alignment V. Linked Lists

Reference slides! C Strings! A string in C is just an array of characters.!!!char string[] = "abc";! How do you tell how long a string is?!

Arrays and Pointers in C. Alan L. Cox

CPSC 3740 Programming Languages University of Lethbridge. Data Types

First of all, it is a variable, just like other variables you studied

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

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

PROGRAMMAZIONE I A.A. 2017/2018

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

Chapter 17 vector and Free Store

Dynamic memory allocation (malloc)

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

Pointers and Memory 1

Lecture 2: C Programm

Lecture 14. Dynamic Memory Allocation

Chapter 8 :: Composite Types

Intermediate Programming, Spring 2017*

Yacoub Sabatin Muntaser Abulafi Omar Qaraeen

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

CSE 374 Programming Concepts & Tools

Syntax and Variables

CS 31: Intro to Systems Arrays, Structs, Strings, and Pointers. Kevin Webb Swarthmore College March 1, 2016

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

Chapter 1 INTRODUCTION SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC.

Pointers, Arrays, and Strings. CS449 Spring 2016

Memory and C/C++ modules

Arrays and Memory Management

Exercise 3 / Ch.7. Given the following array, write code to initialize all the elements to 0: int ed[100]; Hint: It can be done two different ways!

A brief introduction to C programming for Java programmers

CS 2461: Computer Architecture I

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

CS 222: Pointers and Manual Memory Management

Transcription:

Arrays in C C Programming and Software Tools N.C. State Department of Computer Science

Contents Declaration Memory and Bounds Operations Variable Length Arrays Multidimensional Arrays Character Strings sizeof Operator CSC230: C and Software Tools (c) NC State University Computer Science Faculty 2

Arrays Almost any interesting program uses for loops and arrays a[i] refers to i th element of array a numbering starts at 0 Specification of array and index is commutative, i.e., a[i] references the same value as i[a]! days_in_month[0] = 31; 1[days_in_month] = 28; common source of bugs referencing first element as a[1] CSC230: C and Software Tools (c) NC State University Computer Science Faculty 3

Declaring Arrays The declaration determines the 1. element datatype 2. array length (implicit or explicit) 3. array initialization (none, partial, or full) Array length (bounds) can be any constant (integer) expression, e.g., 3, 3*16-20/4, etc. CSC230: C and Software Tools (c) NC State University Computer Science Faculty 4

Declaring 1-D Arrays Explicit length, nothing initialized: int days_in_month[12]; char first_initial[12]; float inches_rain[12]; Explicit length, fully initialized: int days_in_month[12] = {31,28,31,30,31,30,31,31,30,31,30,31 }; char first_initial[12] = { J, F, M, A, M, J, J, A, S, O, N, D }; float inches_rain[12] = {3.5,3.7,3.8,2.6,3.9,3.7,4.0,4.0,3.2,2.9,3.0,3.2}; what happens if you try to initialize more than 12 values?? CSC230: C and Software Tools (c) NC State University Computer Science Faculty 5

Declaring 1-D (cont d) Implicit length + full initialization: int days_in_month[] = {31,28,31,30,31,30,31,31,30,31,30,31 }; char first_initial[] = { J, F, M, A, M, J, J, A, S, O, N, D }; float inches_rain[] = {3.5,3.7,3.8,2.6,3.9,3.7,4.0,4.0,3.2,2.9,3.0,3.2}; The number of values initialized implies the size of the array CSC230: C and Software Tools (c) NC State University Computer Science Faculty 6

Declaring 1-D (cont d) Can initialize just selected elements uninitialized values are cleared to 0 Two styles: int days_in_month[12] = {31,28,31,30,31,30}; char first_initial[12] = { J, F, M }; float inches_rain[12] = {3.5,3.7,3.8,2.6,3.9,3.7,4.0,4.0}; int days_in_month[12] = {[0]=31,[3]=30,[7]=31}; char first_initial[12] = {[2]=`M,[3]= A,[4]= M,[11]= D }; CSC230: C and Software Tools (c) NC State University Computer Science Faculty 7

Declaring 1-D (cont d) Implicit array length and partial initialization?? char first_initial[] = { [0]= J, [2]= M, [8]= S }; How big is this array?? CSC230: C and Software Tools (c) NC State University Computer Science Faculty 8

Memory Layout and Bounds Checking Storage for array int days_in_month[12]; Storage for other stuff Storage for some more stuff (each location shown here is an int) There is NO bounds checking in C i.e., it s legal (but not advisable) to refer to days_in_month[216] or days_in_month[-35]! who knows what is stored there? CSC230: C and Software Tools (c) NC State University Computer Science Faculty 9

Bounds Checking (cont d) References outside of declared array bounds may cause program exceptions ( bus error or segmentation fault ), may cause other data values to become corrupted, or may just reference wrong values Debugging these kinds of errors is one of the hardest errors to diagnose in C common source of bugs referencing outside the declared bounds of an array CSC230: C and Software Tools (c) NC State University Computer Science Faculty 10

Operations on Arrays The only built-in operations on arrays are: address of operator (&) sizeof operator we ll discuss these shortly... Specifically, there are no operators to assign a value to an entire array add two arrays multiply two arrays rearrange (permute) contents of an array etc. CSC230: C and Software Tools (c) NC State University Computer Science Faculty 11

Operations on Arrays? Instead of using built-in operators, write loops to process arrays, e.g. int exam1_grade[num_students], hw1[num_students], hw2[num_students], hw_total[num_students]; for (int j = 0; j < NUM_STUDENTS; j++) { exam1_grade[j] = 100; hw_total[j] = hw1[j] + hw2[j]; } CSC230: C and Software Tools (c) NC State University Computer Science Faculty 12

Variable Length Arrays In C99, array length can be dynamically declared for non-static variables: int i, szar; printf( Enter # of months in year: "); scanf("%d", &szar); int days[szar]; what happens if you attempt to allocate an array of size zero, or of negative size?? CSC230: C and Software Tools (c) NC State University Computer Science Faculty 13

Variable (cont d) However array lengths cannot change dynamically during program execution int sz1, sz2; (void) printf( Enter first # of records: "); (void) scanf("%d", &sz1); int recs[sz1]; do some stuff (void) printf( Enter second # of records: "); (void) scanf("%d", &sz2); int recs[sz2]; Won t work! Compile error! CSC230: C and Software Tools (c) NC State University Computer Science Faculty 14

Multi-Dimensional ( M-D ) Arrays Declaring a multi-dimensional array with explicit length (in all dimensions), no initialization: int xy_array[10][20]; char rgb_pixels[256][256][3]; rows columns Referring to one element of a multi-dimensional array: xyval = xy_array[5][3]; r = rgb_pixels[100][25][0]; color intensity (r, g, or b) CSC230: C and Software Tools (c) NC State University Computer Science Faculty 15

M-D Arrays (cont d) M-D Arrays are really arrays of arrays! i.e., 2-D arrays (xy_array) are arrays of 1-D arrays 3-D arrays (rgb_pixels) are arrays of 2-D arrays, each of which is an array of 1-D arrays etc. The following are all valid references rgb_pixels /* entire array (image) of pixels */ rgb_pixels[9] /* 10 th row of pixels */ rgb_pixels[9][4] /* 5 th pixel in 10 th row */ rgb_pixels[9][4][0] /* red value of 5 th pixel in 10 th row */ CSC230: C and Software Tools (c) NC State University Computer Science Faculty 16

Initializing M-D Arrays With implicit initialization, elements are initialized in leftmost-to-rightmost dimension order, e.g. /* 2-D array with 2 rows and 3 columns */ char s2d[2][3] = { {'a', 'b', 'c'}, {'d', 'e', 'f'} }; for (int i = 0; i < 2; i++) for (int j = 0; j < 3; j++) putchar(s2d[i][j]); The above outputs abcdef CSC230: C and Software Tools (c) NC State University Computer Science Faculty 17

Initializing M-D (cont d) Full initialization, explicit length int i[3][4] = { {0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11} }; Partial initialization, explicit length int i[3][4] = { {0, 1}, {4, 5}, {8, 9} }; CSC230: C and Software Tools (c) NC State 18

Implicit Length for M-D Arrays Only the first dimension (row) length can be omitted OK int i[][3] = { {0, 1, 2}, {4, 5, 6} }; NOT OK int i[2][] = { {0, 1, 2}, {4, 5, 6} }; CSC230: C and Software Tools (c) NC State University Computer Science Faculty 19

Memory Layout of M-D Arrays Laid out in row-major (leftmost-to-rightmost dimension) ordering Storage for array s2d[2][3] a b c d e f 1st row 2nd row Doesn t matter what the order is, in Java; why should we care in C? CSC230: C and Software Tools (c) NC State University Computer Science Faculty 20

Character Strings Strings (i.e., sequence of chars) are a particularly useful 1-D array All the rules of arrays apply, but there are a couple of extra features Initialization can be done in the following styles char s1[] = csc230 ; char s1[] = { c, s, c, 2, 3, 0 }; In the first style, the string is implicitly null-terminated by the compiler i.e., the array is 7 characters long common source of bugs failure to null terminate a string CSC230: C and Software Tools (c) NC State University Computer Science Faculty 21

Character Strings (cont d) Storage for array s1[] c s c 2 3 0 null Null termination is a convenience to avoid the need to specify explicitly the length of a string i.e., functions processing strings can simply look for a null character to recognize the end of the string Ex.: printf() prints string of arbitrary length using format specifier %s (string must be null terminated) \0 (each location shown here is a char) char s1[] = csc203 ; printf ( I m in %s\n, s1); CSC230: C and Software Tools (c) NC State University Computer Science Faculty 22

Character String Concatenation Can initialize a string as a concatenation of multiple quoted initializers: char s1[] = "Now " "is " "the " "time"; printf("%s\n", s1); Output of execution is: Now is the time char s1[] = This is a really long string that would be hard to specify in a single line, so using concatenation is a convenience. ; CSC230: C and Software Tools (c) NC State University Computer Science Faculty 23

The sizeof Operator Not a function call; a C operator returns number of bytes required by a data type Return value is of predefined type size_t #include <stdlib.h> size_t tsz1, tsz2, tsz3; int a; float b[100]; tsz1 = sizeof (a); tsz2 = sizeof (b); tsz3 = sizeof (b[0]); What are these values? CSC230: C and Software Tools NC State Computer Science Faculty 24

The sizeof Operator (cont d) Can also be used to determine the number of elements in an array float b[100]; int nelems; nelems = sizeof (b) / sizeof (b[0]); sizeof() is evaluated at compile time for statically allocated objects CSC230: C and Software Tools NC State Computer Science Faculty 25

Exercise 08a Reverse 10 Write a program that reads 10 integers and prints them in reverse order. Use an array of course. %./reverse10 2 3 5 7 11 13 17 19 23 29 29 23 19 17 13 11 7 5 3 2 CSC230 - C and Software Tools NC State University Computer Science Faculty Reminder: Go to course web page for link to exercise form. Paste code into ideone.com and submit the link. 26

Any Questions? CSC230 - C and Software Tools NC State University Computer Science Faculty 27