Arrays and Pointers1 Arrays of Arrays: We can have arrays of any type, even arrays whose elements are themselves arrays. With two bracket pairs, we obtain.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Lectures 10 & 11.
Programming Languages and Paradigms The C Programming Language.
Lecture 20 Arrays and Strings
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.
Elementary Data Structures: Part 2: Strings, 2D Arrays, Graphs
Programming in C Pointers and Arrays, malloc( ). 7/28/092 Dynamic memory In Java, objects are created on the heap using reference variables and the new.
Kernighan/Ritchie: Kelley/Pohl:
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
1 Introduction to Computing Lecture 11 Character Strings Assist.Prof.Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering
Arrays part 3 Multidimensional arrays, odds & ends.
1 2-D Arrays Overview l Why do we need Multi-dimensional array l 2-D array declaration l Accessing elements of a 2-D array l Declaration using Initializer.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
1 Chapter 9 Arrays and Pointers. 2  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Pointers and Arrays C and Data Structures Baojian Hua
1 CS 201 Array Debzani Deb. 2 Having trouble linking math.h? Link with the following option gcc –lm –o test test.o.
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Chapter 8 Multidimensional Arrays C Programming for Scientists & Engineers with Applications by Reddy & Ziegler.
CNG 140 C Programming (Lecture set 10) Spring Chapter 12 Structures.
 2006 Pearson Education, Inc. All rights reserved Arrays.
CPT: Arrays of Pointers/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to illustrate the use of arrays.
Chapter 8 Arrays and Strings
Comp 248 Introduction to Programming Chapter 6 Arrays Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
1 DATA STRUCTURES: LISTS. 2 LISTS ARE USED TO WORK WITH A GROUP OF VALUES IN AN ORGANIZED MANNER. A SERIES OF MEMORY LOCATIONS CAN BE DIRECTLY REFERENCED.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
0 Chap. 5 Pointers and Arrays 5.3Pointers and Arrays 5.4Address Arithmetic 5.5Character Pointers and Functions 5.6Pointer Arrays; Pointers to Pointers.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 23P. 1Winter Quarter Structs and Enumeration Lecture 23.
21-Feb-02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Multidimensional Arrays Lecture 20 4/3/2002.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
מערכים (arrays) 02 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 15 1 Department of Computer Science-BGU.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
Computer Programming Lecture 8 Arrays. 2 switch-statement Example (3) If use press left arrowIf use press right arrow If use press up arrow If use press.
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
Structured Programming Approach Module VIII - Additional C Data Types Arrays Prof: Muhammed Salman Shamsi.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
More Pointers and Arrays Kernighan/Ritchie: Kelley/Pohl: Chapter 5 Chapter 6.
Review Pointer Pointer Variables Dynamic Memory Allocation Functions.
Arrays and Pointers.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Today’s Material Strings Definition Representation Initialization
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
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.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Week 6 - Friday.  What did we talk about last time?  Loop examples.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
ADVANCED POINTERS. Overview Review on pointers and arrays Common troubles with pointers Multidimensional arrays Pointers as function arguments Functions.
Pointers A pointer type variable holds the address of a data object or a function. A pointer can refer to an object of any one data type; it cannot refer.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Array contiguous memory locations that have the same name and type. Note: an array may contain primitive data BUT an array is a data structure a collection.
19-Feb-02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Arrays, Pointers, Strings Lecture 18 19/2/2002.
Arrays. C++ Style Data Structures: Arrays(1) An ordered set (sequence) with a fixed number of elements, all of the same type, where the basic operation.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
1 ARRAYS AND STRUCTURES. 2 Arrays Array: a set of index and value data structure For each index, there is a value associated with that index. representation.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
C Programming Lecture 15 Two Dimensional Arrays. Two-Dimensional Arrays b The C language allows arrays of any type, including arrays of arrays. With two.
Module 2 Arrays and strings – example programs.
2-D arrays a00 a01 a02 a10 a11 a12 a20 a21 a22 a30 a31 a32
C Programming Language
(PART 2) prepared by Senem Kumova Metin modified by İlker Korkmaz
Programming Languages and Paradigms
Arrays, Pointers, and Strings
Presentation transcript:

Arrays and Pointers1 Arrays of Arrays: We can have arrays of any type, even arrays whose elements are themselves arrays. With two bracket pairs, we obtain a two- dimensional array. To obtain arrays of higher dimension, we simply continue to add brackets. int a[100]; // an one-dimensional array int b[2][7]; // a two-dimensional array int c[5][4][3]; // a three-dimensional array

Arrays and Pointers2 Size of a Multi-dimensional Array: A k-dimensional array has a size for each of its k dimensions. Let si represent the size of the array’s ith dimension, such as int a[s1][s2]…[sk]; then the declaration of the array a allocates space for s1  s2  …  sk elements.

Arrays and Pointers3 Example: int a[3][5]; Col 1Col 2Col 3Col 4Col 5 Row 1a[0][0]a[0][1]a[0][2]a[0][3]a[0][4] Row 2a[1][0]a[1][1]a[1][2]a[1][3]a[1][4] Row 3a[2][0]a[2][1]a[2][2]a[2][3]a[2][4]

Arrays and Pointers4 #define ROWS 3 #define COLS 4 int main(){ int a[ROWS][COLS], i, j, sum = 0; for (i = 0; i < ROWS; ++i) /* fill the array */ for (j = 0; j < COLS; ++j) a[i][j] = i + j; for (i = 0; i < ROWS; ++i){ /* print the array */ for (j = 0; j < COLS; ++j) printf(“a[%d][%d] = %d ”, i, j, a[i][j]); printf(“\n”); } for (i = 0; i < ROWS; ++i) /* sum the array */ for (j = 0; j < COLS; ++j) sum += a[i][j]; printf(“\nsum = %d\n”, sum); }

Arrays and Pointers5 Relationship between pointers and arrays: int a[3][5]; Expressions equivalent to a[i][j] *(a[i] + j) (*(a + i))[j] *(*(a + i) + j) *(&a[0][0] + 5*i + j)

Arrays and Pointers6 Storage Mapping Function: For any array, the mapping between pointer values and array indices is called the storage mapping function. For example: int a[ROWS][COLS]; a[i][j]  *(&a[0][0] + i*COLS + j) Note: the array name a by itself is equivalent to &a[0], a pointer to an array of COLS ints. The base address of the array is &a[0][0], not a.

Arrays and Pointers7 Multi-dimensional Arrays as Formal Parameters: In a function definition, a multi-dimensional array argument must be specified by all sizes except the first dimension. int sum(int a[][5]) int i, j, sum = 0; for (i = 0; i < ROWS; ++i) for (j = 0; j < 5; ++j) sum += a[i][j]; return sum; } Note: the following parameter declarations are equivalent: int a[][5] int (*a)[5] int a[3][5]

Arrays and Pointers8 Initialization: The following three initializations are equivalent. int a[2][3] = {1, 2, 3, 4, 5, 6}; int a[2][3] = {{1, 2, 3}, {4, 5, 6}}; int a[][3] = {{1, 2, 3}, {4, 5, 6}}; If there are no inner braces, then each array elements is initialized in turn (row-wise). If there are fewer values than elements in the array, then the remaining elements are initialized to zero. If the first bracket pair is empty, then the compiler takes the size from the number of inner brace pairs. All sizes except the first must be given explicitly.

Arrays and Pointers9 Another Example: int a[2][2][3] = { {{1, 1, 0}, {2, 0, 0}}, {{3, 0, 0}, {4, 4, 0}} }; /* or equivalently */ int a[][2][3] = { {{1, 1}, {2}}, {{3}, {4, 4}} };

Arrays and Pointers10 Dynamic Allocation: Suppose we want to build a student name list. The program must read its input from keyboard (by calling getline function) and store the input into some kind of table. What king of table? If we use an array of pointers, how to allocate space for each entry?

Arrays and Pointers11 Arrays of Pointers: 2-D arrays contain the same number of elements in each row. For example: char days[][10] = { {‘m’,’o’,’n’,’d’,’a’,’y’,’\0’}, {‘t’,’u’,’e’,’s’,’d’,’a’,’y’,’\0’}, … }; Space is wasted in the rows containing shorter strings. Can we build an array whose rows can vary in length?

Arrays and Pointers12 Ragged Array: A ragged array is an array of pointers where each entry in the array is a pointer to a string (arbitrary length). For example: char *days[] = { “monday”, “tuesday”, “wednesday”, “thursday”, “friday”, “saturday”, “sunday” }; The compiler allocates an array containing 7 elements and assigns each element a pointer to the corresponding string.

Arrays and Pointers13 monday\0 tuesday wednesday thursday friday saturday sunday 2-D Array: * * * * * * * monday\0 tuesday sunday …… Array of pointers:

Arrays and Pointers14 Accessing Elements: Elements in a ragged array can be access in either pointer-based access or array-based access. For example, char *days[] = { “monday”, “tuesday”, “wednesday”, “thursday”, “friday”, “saturday”, “sunday” }; Suppose we want to access the third char of “wednesday”, the following are equivalent: days[2][2] *(days[2] + 2) *(*(days + 2) + 2) days is the base-address of the array of pointers days[k] is the pointer to the kth string

Arrays and Pointers15 Self-Test: char *days[] = { “monday”, “tuesday”, “wednesday”, “thursday”, “friday”, “saturday”, “sunday” }; Expression: *(days[2] + 4) days[3][5] days[4] *(days[5]) days[6][6] **days Value: ‘e’ ‘d’ “friday” ‘s’ ‘\0’ ‘m’

Arrays and Pointers16 Traversing an Array of pointers: #include /* array-based (index) */ void printStrs1(char *s[], int n){ int i; for (i = 0; i < n; i++) printf(“%s\n”, s[i]); } /* pointer-based */ void printStrs2(char **sp, int n){ char ** ep = sp + n; for ( ; sp < ep; sp++) printf(“%s\n”, *sp); }

Arrays and Pointers17 #include #define MAXLEN 80 #define MAXNAMES 100 static char *newStr(char *str){// a static function will be handled as an inline function char * newstr = malloc(strlen(str) + 1); if (newstr != NULL) strcpy(newstr, str); return newstr; } int main(){ int k; char *nameTable[MAXNAMES], name[MAXLEN + 1], *sp; for (k = 0; getline(name, MAXLEN) != -1 && k < MAXAMES; k++){ if ((sp = newStr(name)) != NULL) nameTable[k] =sp; else { printf(“Memory run out\n”); break; } printStr(nameTable, k); }

Arrays and Pointers18 Command-line Arguments: When we run a program, we often provide some initial values the program will work with. For Example: $myprogram filename 222 Two arguments, argc and argv, can be used with the main() to communicate with the operating system, where argc is the number of arguments on the command-line, and argv is an array of pointers to strings containing the various arguments. For the above example: argc == 3 argv[0] == “myprogram” argv[1] == “filename” argv[2] == “222”

Arrays and Pointers19 Passing Arguments to main(): #include int main(int argc, char *argv[]){ int k; printf(“argc = %d\n”, argc); for (k = 0; k < argc; k++) printf(“argv[%d] = %s\n”, k, argv[k]); } $ mytest –o try this argc = 4 argv[0] = mytest argv[1] = -o argv[2] = try argv[3] = this

Arrays and Pointers20 Self-Test: char s1[] = “beautiful big sky country”, s2[] = “how now brown cow”; Expression: strlen(s1) strlen(s2 + 8) strcmp(s1, s2) Statement: printf(“%s”, s1 + 10); strcpy(s1 + 10, s2 + 8); strcat(s1, “s!”); printf(“%s”, s1); Value: 25 9 negative int what is printed big sky country beautiful brown cows!

Arrays and Pointers21 Self-Test: char *p[2][3] = {{“abc”, “defg”, “hi”}, {““jklmno”, “pqrstuvw”, “xyz”}}; Expression: Equivalent expression: ***p p[0][0][0] **p[1] **(p[1] + 2) *(*(p + 1) + 1)[7] (*(*(p + 1) + 1))[7] *(p[1][2] + 2) Value: ‘a’ ‘j’ ‘x’ error ‘w’ ‘z’

Arrays and Pointers22 A Union and Structure Example: typedef enum {AUTO, BOAT, PLANE, SHIP} VTYPE; typedef struct { /* structure for an automobile */ int tires; int fenders; int doors; } AUTOTYPE; typedef struct { /* structure for a boat or ship */ int displacement; char length; } BOATTYPE;

Arrays and Pointers23 typedef struct { char engines; int wingspan; } PLANETYPE; typedef struct { VTYPE vehicle; /* what type of vehicle? */ int weight; /* gross weight of vehicle */ union { /* type-dependent data */ AUTOTYPE car; /* part 1 of the union */ BOATTYPE boat; /* part 2 of the union */ PLANETYPE airplane; /* part 3 of the union */ BOATTYPE ship;/* part 4 of the union */ } vehicle_type; int value; /* value of vehicle in dollars */ char owner[32]; /* owners name */ } VEHICLE;

Arrays and Pointers24 void print_auto(VEHICLE * pv){ printf(“Auto weight = %d\n”, pv->weight); printf(“# of tires: %d\n, # of fenders: %d\n, # of doors: %d\n”, pv->vehicle_type.car.tires, pv->vehicle_type.car.fenders, pv->vehicle_type.car.doors); printf(“Cost = $%d\n”, pv->value); printf(“Owned by %s\n”, pv->owner); /* owners name */ } void print_plane(VEHICLE * pv){ …}; void print_boat(VEHICLE * pv){ …}; void print_ship(VEHICLE * pv){ …};

Arrays and Pointers25 void print_vehicle(VEHICLE * pv){ switch (pv->vehicle){ case AUTO:print_auto(pv); break; case PLANE:print_plane(pv); break; case BOAT:print_boat(pv); break; case SHIP:print_ship(pv); break; default:printf(“Unknown vehicle type\n”); }

Arrays and Pointers26 void main() { VEHICLE v[2], *piper_cub; v[0].vehicle = AUTO; v[0].weight = 2742; /* with a full gas tank */ v[0].vehicle_type.car.tires = 5; /* including the spare */ v[0]. v[0].vehicle_type.car.doors = 2; /* … other initialization of v[0] */ v[1].vehicle = BOAT; v[1].value = 3742; /* trailer not included */ v[1].vehicle_type.boat.length = 20; /* … other initialization of v[1] */ piper_cub = (vehicle*) malloc(sizeof(VEHICLE)); piper_cub->vehicle = PLANE; piper_cub->vehicle_type.airplane.wingspan = 27; /* … other initialization of piper_cub */ print_vehicle(v); print_vehicle(&v[1]); print_vehicle(piper_cub); /* piper_cub is a pointer to VEHICLE */ }