Structs & typedef. Structs 2 Contiguously-allocated region of memory Refer to members within structure by names Members may be of different types Example:

Slides:



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

Question Bank. Explain the syntax of if else statement? Define Union Define global and local variables with example Concept of recursion with example.
Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
Programming in C Chapter 10 Structures and Unions
Compilation and Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
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.
Chapter 6 Structures By C. Shing ITEC Dept Radford University.
C Structures Basics of structures Typedef. Data Hierarchy Byte –8 bits (ASCII character ‘A’ = ) Field –Group of characters (character string “Fred”)
Structures Spring 2013Programming and Data Structure1.
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.
Introduction to C Programming in Unix Environment - II Abed Asi Extended System Programming Laboratory (ESPL) CS BGU Fall 2014/2015 Some slides.
Structures C and Data Structures Baojian Hua
Complex Number Module The code given here relies upon ANSI C’s ability to return a struct. Esakov and Weiss use the argument list to return a pointer to.
. Compilation / Pointers Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
. Plab – Tirgul 4 structs & arrays, file I/O, debugging memory errors.
OOP Etgar 2008 – Recitation 51 Object Oriented Programming Etgar 2008 Recitation 5.
Classes Separating interface from implementation
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 6 : September 6.
Data Representation and Alignment Topics Simple static allocation and alignment of basic types and data structures Policies Mechanisms.
Data Type. A data type defines a set of values that a variable can store along with a set of operations that can be performed on that variable. Common.
Recap, Test 1 prep, Composition and Inheritance. Dates Test 1 – 12 th of March Assignment 1 – 20 th of March.
1 Further C  Multiple source code file projects  Structs  The preprocessor  Pointers.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Functions, Pointers, Structures Keerthi Nelaturu.
Machine-Level Programming 6 Structured Data Topics Structs Unions.
CS 450 MPX P ROJECT A Quick C Review. P OINTERS AND ADDRESSES IN C Check Manual I2 from Dr. Mooney’s website for a complete review of C topics you will.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
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:
11 Introduction to Object Oriented Programming (Continued) Cats.
Today’s Material Aggregate Data Types: Structures and Unions
CS 261 – Data Structures Introduction to C Programming.
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
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.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Structures and Unions in C Alan L. Cox
ECE Application Programming
University of Amsterdam Computer Systems – Data in C Arnoud Visser 1 Computer Systems New to C?
University of Washington Today Lab 3 out  Buffer overflow! Finish-up data structures 1.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 12 – C: structs, linked lists, and casts.
Variables and memory addresses
1 Structures. 2 What is a Structure? Used for handling a group of logically related data items  Examples: Student name, roll number, and marks Real part.
Pointers & References. Pointers Pointer arithmetic Pointers and arrays Pointer-related typedef’s Pointers and const References.
Lecturer: Nguyen Thi Hien Software Engineering Department Home page: hienngong.wordpress.com Chapter 2: Language C++
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.
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.
Structs in C Computer Organization I 1 November 2009 © McQuain, Feng & Ribbens struct Properties The C struct mechanism is vaguely similar.
1 Structures. 2 What is a Structure? Used for handling a group of logically related data items  Examples: Student name, roll number, and marks Real part.
C++ Functions A bit of review (things we’ve covered so far)
Generic Programming in C
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Function: Declaration
Structs (C,C++).
Pointers in C.
CSE 374 Programming Concepts & Tools
Functions Separate Compilation
Structs & typedef Already seen in tirgul.
C Basics.
Heterogeneous Data Structures & Alignment
Machine-Level Programming 6 Structured Data
Built-In (a.k.a. Native) Types in C++
References Revisited CSE 333 Summer 2018
Pointers Pointers point to memory locations
Programming Language C Language.
COP 3330 Object-oriented Programming in C++
Programming in C Pointers and Arrays.
References Revisited CSE 333 Autumn 2018
Structs (C) Already seen in tirgul.
Structs & typedef Already seen in tirgul.
Presentation transcript:

structs & typedef

Structs 2 Contiguously-allocated region of memory Refer to members within structure by names Members may be of different types Example: struct rec { int i; int a[3]; int *p; }; Possible Memory Layout iap 0416

Struct initialization 3 struct s can be initialized in a way similar to arrays: struct rec { int i; int a[3]; int *p; };... int k; struct rec r = { 5, { 0,1,2}, &k }; r.i=1; r.a[0]=5; r.p=&k;

Struct initialization 4 struct s can be initialized in a way similar to arrays: struct rec { int i; int a[3]; int *p; };... int k; struct rec r = { 5, { 0,1,2}, &k }; r.i=1; r.a[0]=5; Do we really need to write struct rec??? r.p=&k;

typedef 5 Synonyms for variable types – make your program more readable Syntax: Example: typedef ; typedef unsigned int size_t;

typedef 6 Synonyms for variable types – make your program more readable typedef struct _Complex { double _real, _imag; } Complex; Complex addComplex(Complex, Complex); Complex subComplex(Complex, Complex); typedef struct _Complex { double _real, _imag; } Complex; Complex addComplex(Complex, Complex); Complex subComplex(Complex, Complex); complex.h

typedef- why? Readibilty: shorter names or dedicated names 7 typedef unsigned int size_t; typedef struct _Complex Complex; typedef unsigned int size_t; typedef struct _Complex Complex;

typedef- why? Portability: 8 #ifdef INT_4_BYTES typedef int int32; typedef short int16; #else typedef long int32; typedef int int16; #endif #ifdef INT_4_BYTES typedef int int32; typedef short int16; #else typedef long int32; typedef int int16; #endif

typedef- why? Generic code: e.g. changing numbers in a data structure from char to int easily Not always recommended 9

Pointers to struct s 10 You can have a pointer to structs the same way you have pointers to built in type.

Access to struct members via pointers 11 struct MyStr { int _a[10]; }; main() { MyStr x; MyStr *p_x = &x; x._a[2] = 3; (*p_x)._a[3] = 5; p_x->_a[4] = 6; }

Structs - Code 12 Offset of each structure member determined at compile time struct rec { int i; int a[3]; int *p; }; iap 0416 r *idx r int *find_a(struct rec *r, int idx) { return &(r->a[idx]); }

Alignment in memory Compiler specific. In MSVC 2012 default params: Note: MSVC compiler has flags to control this ! struct S1 { char c; int i[2]; double v; }; 13 vi[0]ci[1] P+0P+4 P+16P+24

struct Sequential in memory, but may have gaps: sizeof(S1) != sizeof(char)+sizeof(double)+sizeof(int)*2 Member offset determined in compile time Access member with "." e.g. a.i[0], a.v. Access member of struct pointer contents: (*p). or p-> As always, pass by value! struct S1 { char c; int i[2]; double v; }; struct S1 a,*p; struct S1 { char c; int i[2]; double v; }; struct S1 a,*p; vi[0]ci[1] P+0P+4P P+24

15 Structs – old object oriented design 15 Complex.c struct Complex { double _real, _imag; }; struct Complex addComplex(struct Complex, struct Complex); Complex.h #include "Complex.h" // implementation struct Complex addComplex(struct Complex a, struct Complex b) { Complex.c #include "Complex.h" int main() { struct Complex c;... #include "Complex.h" int main() { struct Complex c;... MyProg.c

16 Structs – old object oriented design – Better design – more on this later 16 Complex.c struct _Complex; typedef struct _Complex Complex; Complex* Complex_alloc(); struct _Complex; typedef struct _Complex Complex; Complex* Complex_alloc(); Complex.h #include "Complex.h" struct _Complex {double _real, _imag} Complex* Complex_alloc(double real, double imag) {... #include "Complex.h" struct _Complex {double _real, _imag} Complex* Complex_alloc(double real, double imag) {... Complex.c #include "Complex.h" int main() { Complex* c_ptr= Complex_alloc(3.0, -1.2);... #include "Complex.h" int main() { Complex* c_ptr= Complex_alloc(3.0, -1.2);... MyProg.c

#if – header safety 17 Complex.h: struct Complex {... MyStuff.h: #include "Complex.h" Main.c: #include "MyStuff.h" #include "Complex.h" Error: Complex.h:1: redefinition of `struct Complex' Error: Complex.h:1: redefinition of `struct Complex'

#if – header safety 18 Complex.h (revised): #ifndef COMPLEX_H #define COMPLEX_H struct Complex {... #endif Main.c: #include "MyStuff.h" #include "Complex.h" // no error this time

#pragma once – header safety 19 Complex.h (revised): #pragma once struct Complex {... Main.c: #include "MyStuff.h" #include "Complex.h" // no error this time

structs copying 20 Copy structs using ‘=‘: copy just struct values!!! Complex a,b; a._real = 5; a._imag = 3; b = a; _real = 5 _imag = 3 a: _real = ? _imag = ? b:

structs copying 21 Copy structs using ‘=‘: copy just struct values!!! Complex a,b; a._real = 5; a._imag = 3; b = a; _real = 5 _imag = 3 a: _real = 5 _imag = 3 b:

Arrays in structs copying 22 struct definition: typedef struct Vec { double _arr [MAX_SIZE]; } Vec; Vec addVec(Vec, Vec);... vec.h

Arrays in structs copying 143 copy struct using ‘=‘: Vec a,b; a._arr[0] = 5; a._arr[1] = 3; b = a; _arr = {5,3,?,…} a: _arr = {?,?,?,…} b:

Arrays in structs copying 24 Copy struct using ‘=‘: copy just struct values!!! Vec a,b; a._arr[0] = 5; a._arr[1] = 3; b = a; _arr = {5,3,?,…} a: _arr = {5,3,?,…} b:

25

Pointers in structs copying 26 struct definition: typedef struct Vec { double _arr [MAX_SIZE]; double * _p_arr; } Vec; Vec addVec(Vec, Vec);... vec.h

Pointers in structs copying 27 Copy structs using ‘=‘: copy just struct values!!! Vec a,b; a._arr[0] = 5; a._arr[1] = 3; a._p_arr = a._arr; b = a; _arr = {5,3,?,…} _p_arr = 0x55 a: _arr = {?,?,?,…} _p_arr = ? b:

Pointers in structs copying 28 Copy structs using ‘=‘: copy just struct values!!! Vec a,b; a._arr[0] = 5; a._arr[1] = 3; a._p_arr = a._arr; b = a; _arr = {5,3,?,…} _p_arr = 0x55 a: _arr = {5,3,?,…} _p_arr = 0x55 b: Pointers copied by value!!!

Pointers in structs copying 29 The result: Vec a,b; a._arr[0] = 5; a._arr[1] = 3; a._p_arr = a._arr; b = a; *(b._p_arr) = 8; printf ("%f", a._arr[0]); Vec a,b; a._arr[0] = 5; a._arr[1] = 3; a._p_arr = a._arr; b = a; *(b._p_arr) = 8; printf ("%f", a._arr[0]); // output 8

How to deep copy structs correctly? 30 Implement a clone function: Vec* Vec_clone (const Vec* v) {...

Arrays & structs as arguments 31 When an array is passed as an argument to a function, the address of the 1st element is passed. Structs are passed by value, exactly as the basic types.

Arrays & structs as arguments 32 struct MyStr { int _a[10]; }; void f(int a[]) { a[7] = 89; } void g(MyStr s) { s._a[7] = -1; } main() { MyStr x; x._a[7] = 0; f(x._a); printf("%d\n", x._a[7]); g(x); printf("%d\n", x._a[7]); } Output: 89