0% found this document useful (0 votes)
122 views17 pages

Time: Year, Month, Day, Hour, Minutes, Second Complex Number: Real Part, Imaginary Part Point in A 2-Dimensional Plane: X Axis, y Axis

Structures allow users to define custom data types that can group together different data types under a single name. A structure contains member variables that can be of fundamental data types like int, char, float. Structures provide a way to store multiple related data together as a single unit. Structures must be declared before use to inform the compiler of their contents. Memory is allocated when a structure variable is defined. Individual members can then be accessed using the dot operator. Structures can be used to represent complex user-defined types like a point in 2D space or a complex number.

Uploaded by

suryareddy
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
122 views17 pages

Time: Year, Month, Day, Hour, Minutes, Second Complex Number: Real Part, Imaginary Part Point in A 2-Dimensional Plane: X Axis, y Axis

Structures allow users to define custom data types that can group together different data types under a single name. A structure contains member variables that can be of fundamental data types like int, char, float. Structures provide a way to store multiple related data together as a single unit. Structures must be declared before use to inform the compiler of their contents. Memory is allocated when a structure variable is defined. Individual members can then be accessed using the dot operator. Structures can be used to represent complex user-defined types like a point in 2D space or a complex number.

Uploaded by

suryareddy
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 17

Structures (struct)

• Structure is a user-defined type that can contains other types

• An aggregate data type for holding data of different types (int, char, float)
under one name

• A struct is a derived data type composed of members that are


each fundamental or derived data types.

• A single struct would store the data for one object. An array of
structs would store the data for several objects.

• A struct can be defined in several ways as illustrated in the


following examples:

Good candidates for structures:


Time: year, month, day, hour, minutes, second
Complex number: real part, imaginary part
Point in a 2-dimensional plane: x axis, y axis
Structures
Structure Declaration

• Creates a user-defined data type.


• Gives the compiler a “head’s up” as to what the structure contains.
• Does NOT create an instance of a structure.
• Does NOT allocate any memory.

Structure Declaration Example


tag
keyword

struct pt3d
{
structure
int pt;
braces elements
double x, y, z;
surround
element };
declarations

semicolon required
Declaring Structures (struct)

Does Not Reserve Space Reserves Space

struct my_example struct my_example


{ {
int label; int label;
char letter; char letter;
char name[20];
char name[20];
} mystruct ;
};
/* The name "my_example" is
called a structure tag */
Structure Definition
• Creates an instance of a structure.
• Allocates memory.
• Associates a variable name with that instance.
• Directly analogous to defining a variable of any of the pre-defined data types.

Structure Definition Example

variable
int main(void) name(s)
{
int i;
variable struct pt3d pt1, pt2; struct pt3d
type pt[5]; array
.... variable
return 0;
}
A Point Structure
/* ptstruc.c void main()
* A point structure example {
*/ a.x = 0; a.y = 0; // Origin, left-top point
#include <stdio.h> b.x = 24; b.y = 79;

#define PRINT(x,y) printf(#x " = %d, /* Last text position on a 25 by 80


points */
", x);\ printf(#y " = %d\n", y)
c.x = (a.x + b.x)/2; // calculate middle
struct point point
{
int x; c.y = (a.y + b.y)/2;
int y;
} a, b; PRINT(a.x, a.y);

struct point c; PRINT(b.x, b.y);

PRINT(c.x, c.y);
}
Output of ptstruc,c
a.x = 0, a.y = 0
b.x = 24, b.y = 79
c.x = 12, c.y = 39
User Defined Data Types (typedef)
• The C language provides a facility called typedef for creating synonyms for
previously defined data type names. For example, the declaration:
typedef int Length;
makes the name Length a synonym (or alias) for the data type int.
• The data “type” name Length can now be used in declarations in exactly the same
way that the data type int can be used:
Length a, b, len ;
Length numbers[10] ;

Typedef & Struct


• Often, typedef is used in combination with struct to declare a synonym (or an
alias) for a structure:
typedef struct /* Define a structure */
{
int label ;
char letter;
char name[20] ;
} Some_name ; /* The "alias" is Some_name */
Some_name mystruct ; /* Create a struct variable */
Accessing Elements
• Similar to accessing elements of an array.
– Array: Follow the name of the array with the “structure access operator” (square
brackets) surrounding the offset of the element to be accessed.
– Structure: Follow the name of the structure with the “member access operator”
(a period) followed by the name of the element to be accessed.
• Use the accessed element just like a plain variable of that same type.

Accessing Struct Members


• Individual members of a struct variable may be accessed using the structure
member operator (the dot, “.”):
mystruct.letter ;
Or , if a pointer to the struct has been declared and initialized
Some_name *myptr = &mystruct ;
by using the structure pointer operator (the “->“):
myptr -> letter ;
which could also be written as:
(*myptr).letter ;
Pointers and Structures
• You may recall that the name of an array stands for the address of its zero-th
element.
– Also true for the names of arrays of structure variables.
• Consider the declaration:
struct stud {
int roll;
char dept_code[25];
float cgpa;
} class[100], *ptr ;
– The name class represents the address of the zero-th element of the structure
array.
– ptr is a pointer to data objects of the type struct stud.
• The assignment
ptr = class ;
– will assign the address of class[0] to ptr.
• When the pointer ptr is incremented by one (ptr++) :
– The value of ptr is actually increased by sizeof(stud).
– It is made to point to the next record.
• Once ptr points to a structure variable, the members can be accessed as:
ptr –> roll ;
ptr –> dept_code ;
ptr –> cgpa ;

– The symbol “–>” is called the arrow operator.

• When using structure pointers, we should take care of


operator precedence.
– Member operator “.” has higher precedence than “*”.
• ptr –> roll and (*ptr).roll mean the same thing.
• *ptr.roll will lead to error.

– The operator “–>” enjoys the highest priority among


operators.
• ++ptr –> roll will increment roll, not ptr.
• (++ptr) –> roll will do the intended thing.
Program to add two complex numbers using pointers

void add (complex * x, complex * y, complex * t) {


t->re = x->re + y->re ;
t->im = x->im + y->im ;
typedef struct { }
float re;
float im;
} complex;
main() {
complex a, b, c;
scanf (“%f %f”, &a.re, &a.im);
scanf (“%f %f”, &b.re, &b.im);
add (&a, &b, &c) ;
printf (“\n %f %f”, c,re, c.im);
}
Passing Structures to Functions
• ANSI C Functions can accept structures as arguments and return a structure
/* account.h */
struct address /* strucfun.c */
{ /* Structure and Functions */
#include <stdio.h>
char street[20]; #include <stdlib.h>
char city[15]; struct account getinput(void);
char state[10]; /* get input return a account structure */
unsigned zip; void print(struct account);
}; /* print the whole structure */
struct address *addr_ptr; // a structure
void main()
pointer {
struct account int i;
{ struct account COMPANY;
unsigned acc_no; struct account *aptr; /* define a
unsigned acc_type; structure pointer */
aptr = &COMPANY;
/* coorporate = 0, individual = 1*/ /* get address for a structure pointer */
char name[20]; COMPANY = getinput();
struct address cust_addr; print(*aptr);
}; }
struct account getinput(void) void print(struct account file)
{ {
struct account data; struct account *fptr;
printf("Enter acc_no: "); fptr = &file;
scanf("%u", &data.acc_no);
printf("Enter acc_type: "); printf("Account no : %d\n", fptr ->acc_no);
scanf("%u", &data.acc_type);
fflush(stdin); printf("Account type: %d\n", fptr ->acc_type);
printf("Enter customer name: ");
gets(data.name); printf("Customer : %s\n", fptr ->name);
printf("Enter Street: ");
gets(data.cust_addr.street); printf("Address :%s\n", fptr -cust_addr.street);
printf("Enter City: ");
gets(data.cust_addr.city); printf("City : %s\n", fptr ->cust_addr.city);
printf("Enter State: ");
gets(data.cust_addr.state); printf("State : %s\n", fptr ->cust_addr.state);
printf("Enter Zip: ");
scanf("%d", &data.cust_addr.zip); printf("ZIP code : %u\n", fptr ->cust_addr.zip);
return (data);
} }
Arrays of Structures
• Each element of the array is a structure

// strucary.c
// Array of Structure aptr = COMPANIES;
#include <stdio.h> // get structure array's address for
#include <stdlib.h> // the structure pointer
#include "account.c" for(i = 0; i < N; i++)
#define N 2 {
struct account getinput(void); COMPANIES[i] =
// get input return a getinput();
// account structure putchar('\n');
void print(struct account);
print(*aptr++);
// print the whole structure
}
void main()
}
{
int i;
struct account COMPANY;
struct account *aptr;
// define a structure pointer
struct account COMPANIES[N];
// an array of structures for
// N customers
Self-Referential Structures

• Self-referential structures
– Structure that contains a pointer to a structure of the same type
– Can be linked together to form useful data structures such as lists, queues,
stacks and trees
– Terminated with a NULL pointer (0)
• Diagram of two self-referential structure objects linked together

15 10

Data member
NULL pointer (points to nothing)
and pointer

struct node nextPtr


{ • Points to an object of type
int data; node
struct node • Referred to as a link
*nextPtr;
}
• Ties one node to another
Unions
• Unions look similar to structures. They have identical declaration syntax and
member access, but they serve a very different purpose.

union Utype {
int ival;
float fval;
char *sval;
};

union Utype x, y, z;

• Accessing members of a union is via “.” member operator or, for pointers to
unions, the -> operator.
• A union holds the value of one-variable at a time.
• The compiler allocates storage for the biggest member of the union.
• The type retrieved from the union must be the type most recently stored. Otherwise,
the result is implementation dependent.
• union Utype x;
x.fval = 56.4; /* x holds type float. */
printf("%f\n", x.fval); /* OK. */
printf("%d\n", x.ival); /* Implementationdependent. */

typedef struct { int x, y; int diam; } Circle;


typedef struct { int x1, y1, x2, y2; } Line;
union shape { Circle c; Line l; };
typedef struct {
int type; /* 0 - circle, 1 - line, etc. */
union shape s;
} Shape;
Shape myshape;
myshape.type = 0;
myshape.s.x = 0; myshape.s.y = 0; myshape.s.diam = 10;
Bit-Field Structures
• Optimize storage space by packing several data objects in a single
machine word
• Define and access several objects in a single machine word
• May use bit-wise operating on the bit-field structures

struct modem{
unsigned ready: 1; // reserve 1 bit for ready
unsigned offhook: 2; // reserve 2 bits
unsigned reserved: 13; // 13-bit reserved
} com1;

Example of Accessing bit-field:


com1.ready = 1; // assignment
if(com1.offhook == 2) busy();

You might also like