ECE 103 Engineering ProgrammingChapter 49
Structures Unions, Part 1
Herbert G. Mayer, PSU CSStatus 6/4/2014
Initial content copied verbatim fromECE 103 material developed by
Professor Phillip Wong @ PSU ECE
Syllabus Structure Definition Accessing a Structure Initializing a Structure Pointer to struct Examples
3
Structure Definitions
Simple variables are declared with a single data type and can hold values only of that type.
Example:
/* Arrays for up to sixty students */char Student_Name[60][100];int ID_Number[60];int HW_Scores[60][6];double HW_average[60];
4
A structure allows multiple variables to be grouped together and be referenced as an aggregate variable.
struct tag{
/* Variable declarations listed here */};
tag is the name assigned to the structure. Braces { } delimit the body of the structure. A semicolon is needed after the ending brace. Variables are declared within the structure body.
Each variable is a member of the structure. Structures can have either block or file scope.
5
Example:struct Student_Info{ char Student_Name[100]; int ID_Number; int HW_Scores[6]; float HW_Average;};
Note: This only defines the “layout” of the structure. It does not actually allocate storage for the member variables.
6
Once the structure is defined, a variable can be declared to be of that structure type.
Example:Declare a structure variable for a single student:
struct Student_Info SData;
Student_Name
ID_Number
HW_Scores
SData
HW_Average
…When SData is declared, storage is now allocated to hold the structure’s member variables.
7
Example:Declare an array of structures forsixty students:
struct Student_Info SData[60];
Student_Name
ID_Number
HW_Scores
SData[0]
HW_Average
…
Student_Name
ID_Number
HW_Scores
SData[1]
HW_Average
…
Student_Name
ID_Number
HW_Scores
SData[59]
HW_Average
…
.
.
.
8
Defining a structure can be combined with declaring a variable of that structure type.
Example:struct point3D{ double x, y, z; int color;
} point[1000];
9
The structure tag can be omitted if a named structure is not required.
Example:struct{ double x, y, z; int color;
} point[1000];
Note: If there is no structure tag, it cannot be used for later variable declarations.
10
A typedef can alias away the “struct” part.Example:/* This has separate structure and typedef definitions */struct point3D{ double x, y, z; int color;};typedef struct point3D Point3D;
Point3D pt;
Example:/* This combines the structure and typedef definitions */typedef struct point3D
{double x, y, z;int color;
} Point3D;
Point3D pt;
11
If a typedef is combined with a structure definition, the tag is optional.
Example:typedef struct
{double x, y, z;int color;
} Point3D;
/* Variable declarations */Point3D pt;
Note: If the tag is omitted, then structure variable declarations must also omit the struct keyword.
Example:struct Point3D pt; /* Causes compiler error */
12
Accessing a Structure
To access a member of a structure variable, use the member operator (a period) :
struct_name.member_varname
struct_name is the name of the structure. member_varname is the name of the member
variable within the structure.
To access an array of structures:
struct_varname[index].member_varname
13
Example:/* Structure definition */struct window{ int win_id; int win_ulc_x, win_ulc_y; int win_width, win_height; int win_color; char win_title[80];};
/* Variable declarations */struct window w;struct window win[10];
/* Change the values of some member variables */w.win_id = 5;w.win_id++;strcpy(w.win_title, "Main_Window");
win[3].win_width = 300;win[3].win_height = 250;
14
Example:#include <stdio.h>#define NAMELEN 80#define NUM 3
typedef struct ID_info{
char FirstName[NAMELEN];int Age;
} ID_info_t;
int main (void){
ID_info_t friend[NUM];int k;for (k = 0; k < NUM; k++)
{printf("Enter first name: "); scanf("%s",
friend[k].FirstName);printf("Enter age: "); scanf("%d", &friend[k].Age);
}for (k = 0; k < NUM; k++){
printf("%s %d\n", friend[k].FirstName, friend[k].Age);}return 0;
}
Actual Output:Enter first name: JoeEnter age: 21Enter first name: SaraEnter age: 19Enter first name: FrankEnter age: 20Joe 21Sara 19Frank 20
15
Initializing Structures
A structure variable can be initialized when it is declared. Initial values for the members are enclosed in braces.
Example:struct point3D{ double x, y, z; int color;};
struct point3D pt = {0, 30, 15, 255};
16
Example:struct point3D{
double x, y, z;int color;
};
struct point3D pt[3] =
{{ 0, 30, 15, 255},
{10, 25, 15, 128},
{ 0, 30, 0, 16}};
17
Designated Initializers for Structures
When a structure variable is declared, C99 allows the members of the structure to be initialized by name, if desired.
/* C90 version */#include <stdio.h>
struct data{
int x;int v[2];
};
int main (void){
struct data x = {1, {5, 2}};
return 0;}
// C99 version#include <stdio.h>
struct data{
int x;int v[2];
};
int main (void){
struct data P = {.x=1, .v[0] = 5, .v[1] = 2};
return 0;}
C99
18
Assignment Operator Applied to Structures
Given two structure variables of the same type, one variable can be copied directly to the other using the assignment operator ( = ).
When copying a structure, the value of each member variable is copied, including entire arrays.
If structures can be assigned to each other, can they also be compared using ==, >, <, etc?
Unfortunately, no. This is not legal in C.
19
Example:
struct point3D{
double x, y, z;int color;
};typedef struct point3D Point3D;
Point3D pt1, pt2, pt3;
/* Initialize pt1 */pt1.x = 10; pt1.y = 20; pt1.z = 0; pt1.color = 34;
/* Copy member variables individually */pt2.x = pt1.x; pt2.y = pt1.y; pt2.z = pt1.z;pt2.color = pt1.color;
/* Copy entire structure at once */pt3 = pt1;
20
Example:#include <stdio.h>
#define SIZE 3
typedef struct
{
int x[SIZE];
} array;
int main (void)
{
array P = {{1,4,6}}, Q = {{0}};
int k;
for (k = 0; k < SIZE; k++)
printf("P.x[%d] = %d Q.x[%d] = %d\n", k, P.x[k], k, Q.x[k]);
Q = P; /* Copy entire array by copying structure */
printf("\n");
for (k = 0; k < SIZE; k++)
printf("P.x[%d] = %d Q.x[%d] = %d\n", k, P.x[k], k, Q.x[k]);
return 0;
}
Actual Output:P.x[0] = 1 Q.x[0] = 0P.x[1] = 4 Q.x[1] = 0P.x[2] = 6 Q.x[2] = 0
P.x[0] = 1 Q.x[0] = 1P.x[1] = 4 Q.x[1] = 4P.x[2] = 6 Q.x[2] = 6
21
Pointers to Structures
Variables that point to structures can be declared:
struct tag * var_name;
To dereference a structure pointer, parentheses are needed, since the member operator has higher precedence than the indirection operator. *svar.mvar is incorrectly parsed as *(svar.mvar). (*svar).mvar is the correct dereferencing syntax.
22
Example:
typedef struct point2D{
int x, y;} Point2D;
Point2D point = {0, 0};Point2D * ptr = &point;
/* Access member variable via pointer */(*ptr).x = 1;(*ptr).y = 5;
23
Because the syntax (*ptr).x is clumsy, an alternative syntax is available:
pointer_varname->member_varname
-> is the pointer operator, which consists of a hyphen followed by a greater-than sign.
No whitespace is permitted between – and >
24
Example:
Point2D point;Point2D * ptr;
point.x = 10;printf("%d\n", point.x);
ptr = &point;
(*ptr).x = 10; /* Assign 10 to member x */printf("%d\n", (*ptr).x);
ptr->x = 10; /* This does same thing */printf("%d\n", ptr->x);
25
Example:#include <stdio.h>#define NAMELEN 80#define NUM 3typedef struct ID_info{
char FirstName[NAMELEN];int Age;
} ID_info_t;
int main (void){
ID_info_t friend[NUM], * f = friend; /* f is pointer to friend */int k;for (k = 0; k < NUM; k++)
{printf("Enter first name: "); scanf("%s", (f+k)-
>FirstName);printf("Enter age: "); scanf("%d", &(f+k)->Age);
}for (k = 0; k < NUM; k++){
/* Show access using both pointer and array notation */printf("%s %d\n", (f+k)->FirstName, f[k].Age);
}return 0;
}
Actual Output:Enter first name: JoeEnter age: 21Enter first name: SaraEnter age: 19Enter first name: FrankEnter age: 20Joe 21Sara 19Frank 20