Programming in C Arrays, Structs and Strings. 7/28/092 Arrays An array is a collection of individual data elements that is:An array is a collection of.

Slides:



Advertisements
Similar presentations
Programming in C Chapter 10 Structures and Unions
Advertisements

Data Types in C. Data Transformation Programs transform data from one form to another –Input data  Output data –Stimulus  Response Programming languages.
C Language.
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
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.
Structures Spring 2013Programming and Data Structure1.
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.
Review for Final Exam Dilshad M. NYU. In this review Arrays Pointers Structures Java - some basic information.
Programming in C Pointers and Arrays. 1/14/102 Pointers and Arrays In C, there is a strong relationship between pointers and arrays.In C, there is a strong.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
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
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
1 Homework Turn in HW2 at start of next class. Starting Chapter 2 K&R. Read ahead. HW3 is on line. –Due: class 9, but a lot to do! –You may want to get.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
C structures and unions (Reek, Ch. 10) 1CS 3090: Safety Critical Programming in C.
Chapter 5 - Arrays CSC 200 Matt Kayala 2/27/06. Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays.
Programming in C Pointers and Arrays. 1/14/102 Pointers and Arrays In C, there is a strong relationship between pointers and arrays.In C, there is a strong.
Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
1 Homework HW6 due class 22 K&R 6.6 K&R 5.7 – 5.9 (skipped earlier) Finishing up K&R Chapter 6.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Arrays Part 9 dbg. Arrays An array is a fixed number of contiguous memory locations, all containing data of the same type, identified by one variable.
Cosc237/structures1 Structures aggregate data types record - single variable name for the whole collection composed of several variables - fields,BUT,
Programming in C Structs and Unions. Java vs C Suppose you were assigned a write an application about points and straight lines in a coordinate plane.
GUIDED BY- A.S.MODI MADE BY- 1. SHWETA ALWANI 2. PRIYANKA.
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:
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
5/3/01 Sudeshna Sarkar, CSE, IIT Kharagpur1 Structures Lecture
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
 2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Homework Finishing up K&R Chapter 6 today Also, K&R 5.7 – 5.9 (skipped earlier)
FUNCTION Dong-Chul Kim BioMeCIS UTA 12/7/
Programming in C Chars, Strings and Structs. ASCII The American Standard Code for Information Interchange (ASCII) character set, has 128 characters designed.
ECE 103 Engineering Programming Chapter 50 Structures Unions, Part 2 Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE.
+ Structures and Unions. + Introduction We have seen that arrays can be used to represent a group of data items that belong to the same type, such as.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
Programming in C Arrays, Structs and Strings. 7/28/092 Arrays An array is a collection of individual data elements that is:An array is a collection of.
Introduction to Computers and Programming Class 24 Structures (structs) Professor Avi Rosenfeld.
Struct s (7.4) Used as data aggregates for an entity can be different types of data e.g. for student id, name, GPA, address,... Similar to classes, but.
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.
Announcements You will receive your scores back for Assignment 2 this week. You will have an opportunity to correct your code and resubmit it for partial.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Functions Dr. Sajib Datta Functions A function is a self-contained unit of program code designed to accomplish a particular task. Some functions.
Java Programming Language Lecture27- An Introduction.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
C Structures and Memory Allocation
Computer Organization and Design Pointers, Arrays and Strings in C
User-Written Functions
Structures, Unions, Enumerations
Chapter 10-1: Structure.
C Programming Tutorial – Part I
Student Book An Introduction
Java Review: Reference Types
Programming in C #4 Structs and Unions.
Programming in C Structs and Unions.
Pass by Reference, const, readonly, struct
C Structures, Unions, Bit Manipulations and Enumerations
CS 240 – Lecture 18 Command-line Arguments, Typedef, Union, Bit Fields, Pointers to Functions.
Programming in C Pointers and Arrays.
Structures, Unions, and Enumerations
Presentation transcript:

Programming in C Arrays, Structs and Strings

7/28/092 Arrays An array is a collection of individual data elements that is:An array is a collection of individual data elements that is: –Ordered -- we can count off the elements 0,1,2,3,... –Fixed in size –Homogeneous -- all of the elements have to be of the same type, e.g., int, float, char, etc. In C, each array has two fundamental properties:In C, each array has two fundamental properties: –the element type –the size

7/28/093 Array Example The following code declares an array of 100 integers and initializes the first and last element. Note that C arrays are always indexed from 0 (zero) int scores[100]; scores[0] = 17; scores[99] = 42;

7/28/094 Array Initialization Arrays may be initialized when declaredArrays may be initialized when declared int grades[ 10 ] = { 90, 80, 70 }; double temps [5] = { 23.7, 12.3, 45.6, 5.55, 67.8 }; Or you can let the compiler calculate it’s lengthOr you can let the compiler calculate it’s length int scores[ ] = { 99, 42, 33, 55, 66, 78 };

7/28/095 Arrays in Memory The name of the array refers to the whole array by acting like a pointer (the memory address) of the start of the arrayThe name of the array refers to the whole array by acting like a pointer (the memory address) of the start of the array scores Someone else’s memory Don’t read/write here

7/28/096 2-d Arrays The following code declares a 2-d array of ints and initializes the first and last elementsThe following code declares a 2-d array of ints and initializes the first and last elements int board[10][12]; board[0][0] = 13; board[9][11] = 42; Although conceptually a table with rows and columns, 2-d arrays are implemented as a single contiguous block of memory with elements of the rightmost index next to each other. E.g. board[1][8] comes right before board[1][9]Although conceptually a table with rows and columns, 2-d arrays are implemented as a single contiguous block of memory with elements of the rightmost index next to each other. E.g. board[1][8] comes right before board[1][9]

1/14/107 More typedefs typedefs can be used to simplify complex declarations such as arrays and 2-d arraytypedefs can be used to simplify complex declarations such as arrays and 2-d array –The declaration typedef int ROW[4]; defines ROW as a new name for an array of 4 integers that now be as a data type ROW row1, row2; void printRow( ROW r ); –The declaration typedef int TABLE[2][3]; defines TABLE as a new name for a 2-d array of integers TABLE scores; void printTable( TABLE t);

7/28/098 Arrays and Functions C passes arguments to functions “by value”C passes arguments to functions “by value” A copy of the argument is used in the functionA copy of the argument is used in the function When passing an array by name, a copy of the array’s starting address is passed to the function, not a copy of the array itselfWhen passing an array by name, a copy of the array’s starting address is passed to the function, not a copy of the array itself As a result, references to array elements within the function are also references to the array argument.As a result, references to array elements within the function are also references to the array argument.

7/28/099 Array Argument Example void addTwo( int a[], int size ) { int k; for (k = 0; k < size; k++) a[k] += 2; } int main( ) { int j, scores[3]; scores[0] = 42; scores[1] = 33; scores[2] = 99; addTwo( scores, 3); for (j = 0; j < 3; j++) printf(“%d “, scores[j]); /* 44, 35, 101 */ return 0; }

7/28/0910 No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity. C does allow us to combine related data into a structure using the keyword struct. All data in a struct can be accessed by any code. The general form of a structure definition isBecause C is not an OOP language, there is no way to combine data and code into a single entity. C does allow us to combine related data into a structure using the keyword struct. All data in a struct can be accessed by any code. The general form of a structure definition is struct tag { member1_declaration; member1_declaration; member2_declaration; member2_declaration; member3_declaration; member3_declaration; memberN_declaration; memberN_declaration; }; }; where struct is the keyword, tag names this kind of struct, and member_declarations are variable declarations which define the members. where struct is the keyword, tag names this kind of struct, and member_declarations are variable declarations which define the members. Note the semi-colon

7/28/0911 C struct Example Defining a struct to represent a point in a coordinate planeDefining a struct to represent a point in a coordinate plane struct point { int x;/* x-coordinate */ int y;/* y-coordinate */ }; Given the declarationsGiven the declarations struct point p1; struct point p2; we can access the members of these struct variables: * the x-coordinate of p1 is p1.x * the y-coordinate of p1 is p1.y * the x-coordinate of p2 is p2.x * the y-coordinate of p2 is p2.y point is the struct tag

7/28/0912 Using structs and members Like other variable types, struct variables (e.g. p1, p2) can be passed to functions as parameters and returned from functions as return types.Like other variable types, struct variables (e.g. p1, p2) can be passed to functions as parameters and returned from functions as return types. The members of a struct are variables just like any other and ca be used wherever any other variable of the same type may be used. For example, the members of the can then be used just like any other integer variables.The members of a struct are variables just like any other and ca be used wherever any other variable of the same type may be used. For example, the members of the struct point can then be used just like any other integer variables.

7/28/0913 printPoint.c struct point inputPoint( ) { struct point p; printf(“please input the points x- and y-coordinates: “); scanf(“%d %d”, &p.x, &p.y); return p; } void printPoint( struct point point ) { printf (“( %2d, %2d )”, point.x, point.y); } int main ( ) { struct point endpoint; endpoint = inputPoint( ); printPoint( endpoint ); return 0; }

7/28/0914 struct assignment The contents of a variable may be copied to another variable of the same type using the assignment (=) operatorThe contents of a struct variable may be copied to another struct variable of the same type using the assignment (=) operator After this code is executedAfter this code is executed struct point p1; struct point p2; p1.x = 42; p1.y = 59; p2 = p1;/* structure assignment copies members */ The values of p2’s members are the same as p1’s members. E.g. p1.x = p2.x = 42 and p1.y = p2.y = 59

7/28/0915 struct within a struct A data element in a struct may be another struct (similar to composition in Java / C++). This example defines a line in the coordinate plane by specifying its endpoints as POINT struct s struct line { struct point leftEndPoint; struct point rightEndPoint; }; Given the declarations below, how do we access the x- and y-coodinates of each line’s endpoints? struct line line1, line2;

1/20/1016 Arrays of struct Since a struct is a variable type, we can create arrays of struct s just like we create arrays of int, char, double, etc.Since a struct is a variable type, we can create arrays of struct s just like we create arrays of int, char, double, etc. Write the declaration for an array of 5 line structures name “lines”Write the declaration for an array of 5 line structures name “lines” struct line lines[ 5 ];

1/20/1017 Array of struct Code /* assume same point and line struct definitions */ int main( ) { struct line lines[5]; int k; /* write code to initialize all data members to zero */ for (k = 0; k < 5; k++) { lines[k].leftEndPoint.x = 0; lines[k].leftEndPoint.y = 0; lines[k].rightEndPoint.x = 0; lines[k].rightEndPoint.y = 0; } /* call the printPoint( ) function to print ** the left end point of the 3 rd line */ printPoint( lines[2].lefEndPoint); return 0; }

7/28/0918 Bitfields When saving space in memory or a communications message is of paramount importance, we sometimes need to pack lots of information into a small space. We can use syntax to define “variables” which are as small as 1 bit in size. These variables are known as “bit fields”.When saving space in memory or a communications message is of paramount importance, we sometimes need to pack lots of information into a small space. We can use struct syntax to define “variables” which are as small as 1 bit in size. These variables are known as “bit fields”. struct weather { unsigned int temperature : 5; unsigned int windSpeed : 6; unsigned int isRaining : 1; unsigned int isSunny : 1; unsigned int isSnowing : 1; };

7/28/0919 Using Bitfields struct weather todaysWeather; todaysWeather.temperature = 44; todaysWeather.isSnowing = 0; todaysWeather.windSpeed = 23; /* etc */ if (todaysWeather.isRaining) printf( “%s\n”, “Take your umbrella”); if (todaysWeather.temperature < 32 ) printf( “%s\n”, “Stay home”);

7/28/0920 More on Bit fields Almost everything about bit fields is machine and compiler specific.Almost everything about bit fields is machine and compiler specific. Bit fields may only defined as (unsigned) intsBit fields may only defined as (unsigned) ints Bit fields do not have memory addresses, so the & operator cannot be applied to themBit fields do not have memory addresses, so the & operator cannot be applied to them We’ll see more on this laterWe’ll see more on this later

7/28/0921 Unions A union is a variable type that may hold different type of members of different sizes, BUT only one type at a time. All members of the union share the same memory. The compiler assigns enough memory for the largest of the member types.A union is a variable type that may hold different type of members of different sizes, BUT only one type at a time. All members of the union share the same memory. The compiler assigns enough memory for the largest of the member types. The syntax for defining a union and using its members is the same as the syntax for a struct.The syntax for defining a union and using its members is the same as the syntax for a struct.

7/28/0922 Formal Union Definition The general form of a union definition isThe general form of a union definition is union tag { member1_declaration; member1_declaration; member2_declaration; member2_declaration; member3_declaration; member3_declaration; memberN_declaration; memberN_declaration; }; }; where union is the keyword, tag names this kind of union, and member_declarations are variable declarations which define the members. Note that the syntax for defining a union is exactly the same as the syntax for a struct. where union is the keyword, tag names this kind of union, and member_declarations are variable declarations which define the members. Note that the syntax for defining a union is exactly the same as the syntax for a struct.

1/20/1023 union.c union data { int x; char c[4]; } ; int i; union data item; item.x = 42; printf(“%d, %o, %x”, item.x, item.x, item.x ); for (i = 0; i < 4; i++ ) printf(“%x ”, item.c[i]); printf( “%s”, “\n”); printf(“%s\n”, “size of data = ”, sizeof(data));

7/28/0924 Union vs. Struct SimilaritiesSimilarities –Definition syntax virtually identical –Member access syntax identical DifferencesDifferences –Members of a struct each have their own address in memory. –The size of a struct is at least as big as the sum of the sizes of the members (more on this later) –Members of a union share the same memory. The size of a union is the size of the largest member.

7/28/0925 Using typedef with a struct typedef is often used for struct s to make coding easier for lazy programmers who can’t type well. In this case the struct tag ( point ) is not required.typedef is often used for struct s to make coding easier for lazy programmers who can’t type well. In this case the struct tag ( point ) is not required. typedef int COORDINATE; typedef struct point { COORDINATE x;/* x-coordinate */ COORDINATE y;/* y-coordinate */ } POINT;/* POINT is an alias for this struct */ /* use the alias to declare variables */ POINT p1, p2, endpoint, origin;

7/28/0926 End of Class 3