Structures. Structures (1) u Structures are C’s way of grouping collections of data into a single manageable unit. –This is also the fundamental element.

Slides:



Advertisements
Similar presentations
Incomplete Structs struct B; struct A { struct B * partner; // other declarations… }; struct B { struct A * partner; // other declarations… };
Advertisements

C Structures What is a structure? A structure is a collection of related variables. It may contain variables of many different data types---in contrast.
Programming in C Chapter 10 Structures and Unions
An introduction to pointers in c
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.
1 Structures. 2 User-Defined Types C provides facilities to define one’s own types. These may be a composite of basic types ( int, double, etc) and other.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Programming and Data Structure
Structures Spring 2013Programming and Data Structure1.
Structures in C.
Character String Manipulation. Overview Character string functions sscanf() function snprintf() function.
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.
Pointers in C Rohit Khokher
Structures A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling.
Pointer, malloc and realloc 1. Name entered was 6 char, not enough space to put null terminator 2 Array of char.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8.
Kernighan/Ritchie: Kelley/Pohl:
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
CS100A, Fall 1997, Lecture 241 CS100A, Fall 1997 Lecture 24, Tuesday 25 November (There were no written notes for lecture 23 on Nov. 20.) Data Structures.
CS61C L05 C Structures, Memory Management (1) Garcia, Spring 2005 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c.
CSSE221: Software Dev. Honors Day 27 Announcements Announcements Projects turned in? Projects turned in? The 2 required Angel surveys are due by 9 pm tonight.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
Programming C/C++ on Eclipe Trình bày : Ths HungNM C/C++ Training.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Programming in C Pointer Basics.
'C' Programming With Structure Records Purpose of structures Coding a structure template Defining a new data type Functions which communicate using structures.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Introduction to Data Structures Systems Programming.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Stack and Heap Memory Stack resident variables include:
Advanced Data types and Sorting
1 Pointers and Arrays. 2 When an array is declared,  The compiler allocates sufficient amount of storage to contain all the elements of the array in.
Learners Support Publications Classes and Objects.
Lists, Stacks and Queues in C Yang Zhengwei CSCI2100B Data Structures Tutorial 4.
Introduction to Programming 3D Applications CE Lecture 12 Structure Pointers and Memory Management in C.
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.
Pointers as Structure Members u One reason to use pointers in structure: struct book { float price; char title[50]; char abstract[5000]; }; …… struct book.
5/3/01 Sudeshna Sarkar, CSE, IIT Kharagpur1 Structures Lecture
Introduction to Data Structures Systems Programming Concepts.
1 Structs. 2 Defining a Structure Often need to keep track of several pieces of information about a given thing. Example: Box We know its length width.
CS 261 – Data Structures C Pointers Review. C is Pass By Value Pass-by-value: a copy of the argument is passed in to a parameter void foo (int a) { a.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
1 CSC103: Introduction to Computer and Programming Lecture No 24.
Topic 4: C Data Structures CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Pointer Arithmetic (1) u When a pointer variable points to an array element, there is a meaning of adding or substracting an integer to/from the pointer.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Advanced Pointer Topics. Pointers to Pointers u A pointer variable is a variable that takes some memory address as its value. Therefore, you can have.
CSE 251 Dr. Charles B. Owen Programming in C1 structs Aggregating associated data into a single variable Box width length height Circle radius int main()
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.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Sudeshna Sarkar, CSE, IIT Kharagpur1 Structure and list processing Lecture
1 Linked List. 2 List A list refers to a sequence of data items  Example: An array The array index is used for accessing and manipulation of array elements.
STRUCTURES. INTRODUCTION A structure is same as that of records. It stores related information about an entity. Structure is basically a user defined.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
1 Structures & Unions. 2 User-Defined Types C provides facilities to define one’s own types. These may be a composite of basic types ( int, double, etc)
Pointers (Revision). 2 Overview Revision of Pointers Pointers and structs Basic Pointer Arithmetic Pointers and Arrays.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
LINKED LISTS.
C Programming Tutorial – Part I
Programming in C Pointer Basics.
Classes and Objects.
Programming in C Pointer Basics.
Linked List.
Java Programming Language
Programming in C Pointer Basics.
Presentation transcript:

Structures

Structures (1) u Structures are C’s way of grouping collections of data into a single manageable unit. –This is also the fundamental element of C upon which most of C++ is built (i.e., classes). –Similar to Java's classes. u An example: –Defining a structure type: struct coord { int x ; int y ; }; –This defines a new type struct coord. No variable is actually declared or generated.

Structures (2) u Define struct variables: struct coord { int x,y ; } first, second; u Another Approach: struct coord { int x,y ; }; struct coord first, second; /* declare variables */ struct coord third;

Structures (3) u You can even use a typedef if your don't like having to use the word “struct” typedef struct coord coordinate; coordinate first, second; u In some compilers, and all C++ compilers, you can usually simply say just: coord first, second;

Structures (4) u Access structure variables by the dot (.) operator u Generic form: structure_var.member_name u For example: first.x = 50 ; second.y = 100; u These member names are like the public data members of a class in Java (or C++). –No equivalent to function members/methods. u struct_var.member_name can be used anywhere a variable can be used: –printf ("%d, %d", second.x, second.y ); –scanf("%d, %d", &first.x, &first.y);

Structures (5) u You can assign structures as a unit with = first = second; instead of writing: first.x = second.x ; first.y = second.y ; u Although the saving here is not great –It will reduce the likelihood of errors and –Is more convenient with large structures u This is different from Java where variables are simply references to objects. first = second; makes first and second refer to the same object.

Structures Containing Structures u Any “type” of thing can be a member of a structure. u We can use the coord struct to define a rectangle struct rectangle { struct coord topleft; struct coord bottomrt; } ; u This describes a rectangle by using the two points necessary: struct rectangle mybox ; u Initializing the points: mybox.topleft.x = 0 ; mybox.topleft.y = 10 ; mybox.bottomrt.x = 100 ; mybox.bottomrt.y = 200 ;

An Example #include struct coord { int x; int y; }; struct rectangle { struct coord topleft; struct coord bottomrt; }; int main () { int length, width; long area; struct rectangle mybox; mybox.topleft.x = 0; mybox.topleft.y = 0; mybox.bottomrt.x = 100; mybox.bottomrt.y = 50; width = mybox.bottomrt.x – mybox.topleft.x; length = mybox.bottomrt.y – mybox.topleft.y; area = width * length; printf ("The area is %ld units.\n", area); }

Structures Containing Arrays u Arrays within structures are the same as any other member element. u For example: struct record { float x; char y [5] ; } ; u Logical organization: floatchar[5] record

An Example #include struct data { float amount; char fname[30]; char lname[30]; } rec; int main () { struct data rec; printf ("Enter the donor's first and last names, \n"); printf ("separated by a space: "); scanf ("%s %s", rec.fname, rec.lname); printf ("\nEnter the donation amount: "); scanf ("%f", &rec.amount); printf ("\nDonor %s %s gave $%.2f.\n", rec.fname,rec.lname,rec.amount); }

Arrays of Structures u The converse of a structure with arrays: u Example: struct entry { char fname [10] ; char lname [12] ; char phone [8] ; } ; struct entry list [1000]; u This creates a list of 1000 identical entry(s). u Assignments: list [1] = list [6]; strcpy (list[1].phone, list[6].phone); list[6].phone[1] = list[3].phone[4] ;

An Example #include struct entry { char fname [20]; char lname [20]; char phone [10]; } ; int main() { struct entry list[4]; int i; for (i=0; i < 4; i++) { printf ("\nEnter first name: "); scanf ("%s", list[i].fname); printf ("Enter last name: "); scanf ("%s", list[i].lname); printf ("Enter phone in format: "); scanf ("%s", list[i].phone); } printf ("\n\n"); for (i=0; i < 4; i++) { printf ("Name: %s %s", list[i].fname, list[i].lname); printf ("\t\tPhone: %s\n", list[i].phone); }

Initializing Structures u Simple example: struct sale { char customer [20] ; char item [20] ; int amount ; }; struct sale mysale = { "Acme Industries", "Zorgle blaster", 1000 } ;

Initializing Structures u Structures within structures: struct customer { char firm [20] ; char contact [25] ; }; struct sale { struct customer buyer ; char item [20] ; int amount ; } mysale = { { "Acme Industries", "George Adams"}, "Zorgle Blaster", 1000 } ;

Initializing Structures u Arrays of structures struct customer { char firm [20] ; char contact [25] ; } ; struct sale { struct customer buyer ; char item [20] ; int amount ; } ; struct sale y1990 [100] = { { { "Acme Industries", "George Adams"}, "Left-handed Idiots", 1000 }, { { "Wilson & Co.", "Ed Wilson"}, "Thingamabob", 290 } } ;

Pointers to Structures struct part { float price ; char name [10] ; } ; struct part *p, thing; p = &thing; /* The following three statements are equivalent */ thing.price = 50; (*p).price = 50; /* () around *p is needed */ p -> price = 50;

Pointers to Structures u p is set to point to the first byte of the struct variable thing.pricething.name [ ] p

Pointers to Structures struct part * p, *q; p = (struct part *) malloc( sizeof(struct part) ); q = (struct part *) malloc( sizeof(struct part) ); p -> price = ; strcpy( p -> name, "hard disk" ); (*q) = (*p); q = p; free(p); free(q); /* This statement causes a problem !!! Why? */

Pointers to Structures u You can allocate a structure array as well: { struct part *ptr; ptr = (struct part *) malloc(10 * sizeof(struct part) ); for( i=0; i< 10; i++) { ptr[ i ].price = 10.0 * i; sprintf( ptr[ i ].name, "part %d", i ); } …… free(ptr); }

Pointers to Structures u You can use pointer arithmetic to access the elements of the array: { struct part *ptr, *p; ptr = (struct part *) malloc(10 * sizeof(struct part) ); for( i=0, p=ptr; i< 10; i++, p++) { p -> price = 10.0 * i; sprintf( p -> name, "part %d", i ); } …… free(ptr); }

Pointer as Structure Member struct node{ int data; struct node *next; }; struct node a,b,c; a.next = &b; b.next = &c; c.next = NULL; NULL abc a.data = 1; a.next->data = 2; /* b.data =2 */ a.next->next->data = 3; /* c.data = 3 */ c.next = (struct node *) malloc(sizeof(struct node)); ……

Assignment Operator vs. memcpy u This assign a struct to another { struct part a,b; b.price = 39.99; b.name = "floppy"; a = b; } u Equivalently, you can use memcpy #include …… { struct part a,b; b.price = 39.99; b.name = "floppy"; memcpy(&a,&b,sizeof(part)); }

Array Member vs. Pointer Member struct book { float price; char name[50]; }; int main() { struct book a,b; b.price = 19.99; strcpy(b.name, "C handbook"); a = b; strcpy(b.name, "Unix handbook"); puts(a.name); puts(b.name); }

Array Member vs. Pointer Member int main() { struct book a,b; b.price = 19.99; b.name = (char *) malloc(50); strcpy(b.name, "C handbook"); a = b; strcpy(b.name, "Unix handbook"); puts(a.name); puts(b.name); free(b.name); } struct book { float price; char *name; }; A function called strdup() will do the malloc() and strcpy() in one step for you!

Passing Structures to Functions (1) u Structures are passed by value to functions –The parameter variable is a local variable, which will be assigned by the value of the argument passed. –Unlike Java. u This means that the structure is copied if it is passed as a parameter. –This can be inefficient if the structure is big. v In this case it may be more efficient to pass a pointer to the struct. u A struct can also be returned from a function.

Passing Structures to Functions (2) struct book { float price; char abstract[5000]; }; void print_abstract( struct book *p_book) { puts( p_book->abstract ); }; struct pairInt { int min, max; }; struct pairInt min_max(int x,int y) { struct pairInt pair; pair.min = (x > y) ? y : x; pair.max = (x > y) ? x : y; return pairInt; } int main(){ struct pairInt result; result = min_max( 3, 5 ); printf("%d<=%d", result.min, result.max); }