A Short Review Arrays, Pointers and Structures. What is an Array? An array is a collection of variables of the same type and placed in memory contiguously.

Slides:



Advertisements
Similar presentations
UNIT IV.
Advertisements

UNIT 9: Pointers Data Variable and Pointer Variable Pass by Reference
Chapter 9 – One-Dimensional Numeric Arrays. Array u Data structure u Grouping of like-type data u Indicated with brackets containing positive integer.
Etter/Ingber Arrays and Matrices. Etter/Ingber One-Dimensional Arrays 4 An array is an indexed data structure 4 All variables stored in an array are of.
CSC141- Introduction to Computer Programming
Chapter 8: Arrays.
C Language.
Pointers. 2 A pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address.
Senem KUMOVA METİN CS FALL 1 POINTERS && ARRAYS CHAPTER 6.
Call By Address Parameters (Pointers) Chapter 5. Functions that “return” more than a single value What if we need more than one value to be returned from.
Introduction to Programming Lecture 15. In Today’s Lecture Pointers and Arrays Manipulations Pointers and Arrays Manipulations Pointers Expression Pointers.
Programming and Data Structure
Structure.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
An Array A sequence of elements of a particular type Each element in the array has an index which gives its position in the sequence An array is declared.
Introduction to Application Programming IST 256 Application Programming for Information Systems Xiaozhong Liu
Arrays. Memory organization Table at right shows 16 bytes, each consisting of 8 bits Each byte has an address, shown in the column to the left
Topic 9 – Introduction To Arrays. CISC105 – Topic 9 Introduction to Data Structures Thus far, we have seen “simple” data types. These refers to a single.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
Friday, December 29, 2006 Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration. - Stan Kelly-Bootle.
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
Arrays.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
C Static Arrays Pepper. What is an array? Memory locations – same type – next to each other (contiguous) – Same name – Indexed by position number of type.
Arrays in C++ Numeric Character. Structured Data Type A structured data type is a type that stores a collection of individual components with one variable.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
Array Cs212: DataStructures Lab 2. Array Group of contiguous memory locations Each memory location has same name Each memory location has same type a.
CSE 251 Dr. Charles B. Owen Programming in C1 Pointers, Arrays, Multidimensional Arrays Pointers versus arrays – Lots of similarities How to deal with.
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
Chapter 8: Arrays and Functions Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
CS102 Introduction to Computer Programming Chapter 9 Pointers.
Foundation Studies Course M.Montebello Arrays Foundation Studies Course.
Data Structure and c K.S.Prabhu Lecturer All Deaf Educational Technology.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Pointers *, &, array similarities, functions, sizeof.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Arrays. Collections We would like to be able to keep lots of information at once Example: Keep all the students in the class Grade each one without writing.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
COMPUTER PROGRAMMING. Array C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An.
POINTERS IN C. Introduction  A pointer is a variable that holds a memory address  This address is the location of another object (typically another.
1 Parameter passing Call by value The caller evaluates the actual parameters and passes copies of their values to the called function. Changes to the copies.
C++ Array 1. C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used.
1 CSC103: Introduction to Computer and Programming Lecture No 17.
Introduction to programming in java Lecture 21 Arrays – Part 1.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Windows Programming Lecture 03. Pointers and Arrays.
Basic Concepts:- Invalid use of Address Operator &75 &(‘a’) &(a+b)
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Array in C# Array in C# RIHS Arshad Khan
Pointers and Pointer-Based Strings
TK1114 Computer Programming
Basic notes on pointers in C
Variables ,Data Types and Constants
2008/11/24: Lecture 19 CMSC 104, Section 0101 John Y. Park
2008/11/24: Lecture 19 CMSC 104, Section 0101 John Y. Park
Declaration, assignment & accessing
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays ICS2O.
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays I Handling lists of data.
Pointers and Pointer-Based Strings
C Programming Pointers
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Presentation transcript:

A Short Review Arrays, Pointers and Structures

What is an Array? An array is a collection of variables of the same type and placed in memory contiguously. The set of data of data in an array is only given one name and the indices are used to differentiate each of the data. The array is important to avoid redundancy of variable declaration and for easy access of data that are placed contiguously in memory. It is the job of the programmer to ensure that the array is large enough to hold what the program will put in them.

One Dimensional Array Syntax Declaration: var_name[size]; var_name[size] = {optional initialization data}; Total Size of the Array in bytes: total bytes = sizeof(base type) * number of elements a[0]a[1]a[2]a[3]a[4]a[5]a[6]

One Dimensional Array Example: int num[5]= { 2, 4, 3, 10, 20}; Index Data num[0] num[1] num[2] … Address &num[0] &num[1] &num[2] … or num Note: Min Index =0 Max Index = size -1 Important: The name of the array is the starting address of the array.

One Dimensional Array Sample Program : Compute Sum of Array Inputs 1/* Filename: SumArray.c Program Description: Ask 5 integers and compute the sum. Programmer: Pedro de la Cruz Date Written: May 29,2005 */ Sample Output: Enter a number: 3 Enter a number: 1 Enter a number: 2 Enter a number: 5 Enter a number: 2 Sum = #include int main(void) { int num[5]; int x, sum=0; for(x=0; x<5; x++) { printf(Enter a number: ); scanf(%d, &num[x]); } for(x=0; x<5; x++) sum += num[x]; printf(\nSum=%d, sum); }

FF04 func1(int *a) /*pointer */ {. } Passing One Dimensional Arrays Example: a[0]a[1]a[2]a[3]a[4]a[5]a[6] FF00FF main(void) { int a[7]; func1(a);. } func1(int a[7]) /*sized array */ {. } func1(int a[ ]) /*unsized array */ {. }

7 Syntax Declaration: array_name[row][column] = {optional initialization data}; Example: int num[3][4] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 1, 0}; Note: Min Col & Row =0 Max Row = Row – 1 Max Col = Column – 1 Size of array = col x row x size of data Important: When the name of the array is used with only 1 index specifying the row, it refers to the address of the first element of the row Column Row Data = num[0][0] Address = &num[0][0] or num[0] Two Dimensional Array

8 Sample Program : Fill a Two-dimensional Array 1/* Filename: Function1.c Program Description: Ask 6 integers and place it in a 2x3 array. Programmer: Pedro de la Cruz Date Written: May 29,2005 */ Sample Output: Enter a number: 1 Enter a number: 10 Enter a number: 2 Enter a number: 20 Enter a number: 3 Enter a number: #include int main(void) { int x[2][3]; int row, col; for(row=0; row<3; row++) { for(col=0; col<2; col++) { printf(Enter a number: ); scanf(%d, &num[row][col]); } Two Dimensional Array

9 Multidimensional arrays can have three, four or more dimensions. Example: 3-Dimensional Array Row Column Plane Syntax: array_name[plane][row][column] int table[3][5][4] = { { /*Plane 0*/ {0,1,2,3}, /*Row 0*/ {1,2,3,4}, /*Row 1*/ {3,4,5,6}, /*Row 2*/ {4,5,6,7}, /*Row 3*/ {5,6,7,8}, /*Row 4*/ } Multi-Dimensional Array

10 Multi-Dimensional Array Sample Program : Multidimensional Array 1/* Filename: MultiDim.c Program Description: Multidimensional Array sample Programmer: Pedro de la Cruz Date Written: May 29,2005 */ Output: #include main() { int table[3][3][4]= { { /*Plane 0*/ {0,1,2,3}, {1,2,3,4}, {2,3,4,5}, } }; int plane, row, col; for(plane=0;plane<1; plane++) { for(row=0; row<3; row++) { for(col=0; col<4; col++) printf(\t%d, table[plane][row][col]); printf(\n); }

Arrays and Pointers Closely related in C char p [10]; p = = &p[0] TRUE Example: one – dimensional arrays int *p, i [10]; p = i; p [5] = 100; /* assign using index */ *(p + 5) = 100;/*assign using pointer arithmetic */

Arrays and Pointers Example: two dimensional arrays assuming that a is a 10 by 10 array a = = &a [0] [0] a [j] [k] is equivalent to *((*a) + (j row length) + k)

Allocated Arrays In C, you can dynamically allocate and free memory by using the standard library routines malloc( ), which allocates memory and returns a void * pointer to the start of it, and free( ) which returns previously allocated memory to the heap for possible reuse. Example: /* allocating 1000 bytes of memory */ char *p; p = malloc(1000);

/* Print a string backwards using dynamic allocation. */ # include int main (void) { char *s; int t; s = malloc (80); if (!s) { printf (memory request failed\n) ; return 1; } gets (s); for (t= strlen (s) – 1; t > = 0; t - - ) printf ( %c, s [t] ); free (s); return 0; }

Seatwork Create a program that will save the following data in ·

What is a Pointer? A pointer is a special type of variable that contains a memory address which could be used to access data Data Variable int x=5; Pointer Variable p=FF00 x=5 &x data address x = data inside address &x &x = address p = address *p = the data inside address p int *p; p=&x; x=5 &x =FF00

What is a Pointer? 1. A pointer provides the means with which functions can modify their calling arguments. 2. A pointer is used to support Turbo Cs dynamic allocation system. 3. The use of pointers can improve the efficiency of certain routines 4. A pointer is commonly used to support certain data structures such as linked lists and binary trees.

Pointer Variables A pointer declaration consists of a base type, an *, and the variable name. Syntax Declaration: *var_name; Defines what type of variables the pointer can point to.

Pointer Operators Two special pointer operators: * & & is a unary operator that returns the memory address of its operand * is the complement of &; a unary operator that returns the value of the variable located at the address that follows

Pointer Expressions Pointer assignments As with any variable, a pointer may be used on the right-hand side of assignment statements to assign its value to another pointer Pointer arithmetic Arithmetic operations are performed to the pointer relative to its base type Addition and subtraction of a pointer and an integer Subtraction of a pointer from another pointer (only when it makes sense)

Pointer Expressions Pointer comparisons It is possible to compare two pointers in a relational expression Generally used when two or more pointers are pointing to a common object

Dynamic Allocation Functions Upon compilation Program code Global data Stack Heap An area of free memory managed by Cs dynamic allocation functions

Dynamic Allocation Functions This code fragment allocates 25 bytes of memory char *p; p = malloc(25); No type cast is used because the pointer type is converted automatically to the same type as the pointer variable

Dynamic Allocation Functions Another example: int *p; p = malloc(50*sizeof(int)); It is imperative to check the value returned by malloc( ) to make sure that it is not null before using the pointer. if((p=malloc(100))==NULL) { printf(Out of memory. \n); exit(1); }

Find the error in this program #include main(void) { char *p1, s[80]; p1 = s; do { gets(s); while (*p1) printf(%d, *p1++); } while (strcmp(s, done)); return 0; }

Pointers to Pointers A pointer to a pointer is a form of multiple indirection, or a chain of pointers Single Indirection value address PointerVariable Multiple Indirection address value Pointer Variable

Pointers to Pointers A variable that is a pointer to a pointer must be declared as such float **newbalance; In order to acess the target value indirectly pointed to by a pointer to a pointer, the asterisk operator must be applied twice as shown: printf( %f,**newbalance);

Initializing Pointers By convention, a pointer that is pointing to nowhere should be given the value null to signify that is points to nothing

Pointers to Functions Even though a function is not a variable, it still has a physical location in memory that can be assigned to a pointer Read on how the address of a function is obtained Read on how to create an array of function pointers for user-defined functions

Problems with Pointers main(void) { int x, *p; x=10; *p = x; return 0; } main(void) { int x, *p; x = 10; p = x; printf(%d, *p); return 0; }

Seatwork Predict the output: int main(void) { int num[5] = {10,20,30,40,50}; int *p1, *p2; p1= num; p2 = p1; *p1 = *p1++ + *p2 + 5; *p2 = *(p1+2) + 10; printf(\n%d, *p1); printf(\n%d, *p2); return 0; }

Structures The C language gives you five ways to create custom data types. One of these is through the creation of structures.

What is a Structure? The structure is a collection of variables referenced under one name, providing a convenient means of keeping related information together.

Structures struct addr { char name[30]; char street[40]; char city[20]; char state[3]; unsigned long int zip; }; Structure Declaration Structure Elements Tells the compiler that a structure is being declared Ends with a semicolon because it is a statement Structure name or tag or type specifier

Structures To declare an actual variable with this structure struct addr addr_info; 30 bytes 40 bytes 20 bytes 3 bytes 4 bytes name street city state zip addr_info

Structures struct addr { char name[30]; char street[40]; char city[20]; char state[3]; unsigned long int zip; } addr_info, binfo, cinfo; Declaration of variables with structure declaration

Structures If you need only one structure, no structure name is needed struct { char name[30]; char street[40]; char city[20]; char state[3]; unsigned long int zip; } addr_info;

Referencing Structure Elements Individual structure elements are referenced by using the. (dot operator) Example: addr_info.zip = 12345; printf(%ld, addr_info.zip); gets(addr_info.name);

Arrays of Structures struct addr addr_info[100]; printf(%ld, addr_info[2].zip);

Passing Structures to Functions Passing Structure Elements to Functions struct fred { char x; int y; float z; char s[10]; } mike; func1(mike.x); func2(mike.y); func(mike.s[2]); func1(&mike.x); func2(&mike.y); func(&mike.s[2]); func(mike); void func(struct fred parm) { }

Structure Pointers struct bal { float balance; char name[80]; } person; struct bal *p; p = &person; p->balance;