Working with Structures. Structure Declaration ä Creates a user-defined data type. ä Gives the...
-
Upload
silvester-mccarthy -
Category
Documents
-
view
215 -
download
2
Transcript of Working with Structures. Structure Declaration ä Creates a user-defined data type. ä Gives the...
Working with StructuresWorking with Structures
Structure DeclarationStructure Declaration
Creates a user-defined data type.Creates a user-defined data type. Gives the compiler a “head’s up” as to what Gives the compiler a “head’s up” as to what
the structure contains.the structure contains. Does NOT create an instance of a structure.Does NOT create an instance of a structure. Does NOT allocate any memory.Does NOT allocate any memory.
Structure Declaration ExampleStructure Declaration Example
struct pt3d{int pt;double x, y, z;
};
keywordkeyword
bracesbracessurroundsurroundelementelementdeclarationsdeclarations
tagtag
semicolon requiredsemicolon required
structurestructureelementselements
Structure DefinitionStructure Definition
Creates an instance of a structure.Creates an instance of a structure. Allocates memory.Allocates memory. Associates a variable name with that instance.Associates a variable name with that instance. Directly analogous to defining a variable of Directly analogous to defining a variable of
any of the pre-defined data types.any of the pre-defined data types.
Structure Definition ExampleStructure Definition Example
int main(void){int i;struct pt3d pt1, pt2; struct pt3d pt[5];....return 0;
}
variablevariabletypetype
variablevariablename(s)name(s)
arrayarrayvariablevariable
Typedef simplifies the syntaxTypedef simplifies the syntax
AlmostAlmost identical to #define statement. identical to #define statement. Performs text replacement.Performs text replacement. ““distributes” any pointer de-reference operators.distributes” any pointer de-reference operators.
Syntax:Syntax:
typedef data-type alias;typedef data-type alias;
Example:Example:
typedef unsigned int size_t;typedef unsigned int size_t;
typedef struct pt3d PT3D;typedef struct pt3d PT3D;
Everything to this pointEverything to this point
typedef struct pt3d PT3D;
struct pt3d{
int pt;double x, y, z;
};
int main(void){
int i;PT3D pt1;PT3D pt[5];....return 0;
}
Typedef can appearTypedef can appearbefore structure declarationbefore structure declaration
Structure declaration outsideStructure declaration outsideany function to make it haveany function to make it haveglobal scopeglobal scope
Accessing ElementsAccessing Elements
Similar to accessing elements of an array.Similar to accessing elements of an array. Array: Follow the name of the array with the “structure Array: Follow the name of the array with the “structure
access operator” (square brackets) surrounding the access operator” (square brackets) surrounding the offset of the element to be accessed.offset of the element to be accessed.
Structure: Follow the name of the structure with the Structure: Follow the name of the structure with the “member access operator” (a period) followed by the “member access operator” (a period) followed by the name of the element to be accessed.name of the element to be accessed.
Use the accessed element just like a plain variable Use the accessed element just like a plain variable of that same type.of that same type.
Accessing Elements ExamplesAccessing Elements Examples
int j;int j;
int k[12];int k[12];
PT3D point;PT3D point;
j = 5;j = 5;
k[j] = 42;k[j] = 42;
point.pt = k[j];point.pt = k[j];
j = point.pt + 3;j = point.pt + 3;
Pointers to StructuresPointers to Structures
Work just like pointers to other data types.Work just like pointers to other data types. Use the “indirection operator” (asterisk) to “de-Use the “indirection operator” (asterisk) to “de-
reference) the pointer in order to get at the reference) the pointer in order to get at the value being pointed to.value being pointed to.
Treat the dereferenced pointer the same as the Treat the dereferenced pointer the same as the name of a variable of the type being pointed to.name of a variable of the type being pointed to.
Structure Pointer ExamplesStructure Pointer Examples
int j, *m;int j, *m;
int k[12];int k[12];
PT3D point, *p;PT3D point, *p;
m = &j;m = &j;
p = &point;p = &point;
*m = 5; // same as j = 5;*m = 5; // same as j = 5;
k[j] = 42;k[j] = 42;
(*p).pt = k[j]; // same as point.pt = k[j];(*p).pt = k[j]; // same as point.pt = k[j];
j = (*p).pt + 3; // same as j = point.pt + 3;j = (*p).pt + 3; // same as j = point.pt + 3;
Why (*p).pt and not just *p.pt ?Why (*p).pt and not just *p.pt ?
Highest precedence operators: Highest precedence operators: ()(), , [][], , .., , ->-> De-reference is second in precedence.De-reference is second in precedence. The code fragment:The code fragment:
*p.pt*p.pt compiles as compiles as *(p.pt)*(p.pt) The operand on the left side of the member access The operand on the left side of the member access
operator must be a variable of structure type.operator must be a variable of structure type. But But pp is not a variable of structure type - it points is not a variable of structure type - it points
to a variable of structure type.to a variable of structure type. So we must override the precedence and force the So we must override the precedence and force the
pointer to be de-referenced first using parentheses.pointer to be de-referenced first using parentheses.
Structure IndirectionStructure Indirection
De-referencing structure pointers very common.De-referencing structure pointers very common. Failing to override operator precedence very Failing to override operator precedence very
common.common. A different operator is available specifically for A different operator is available specifically for
this purpose.this purpose. If the left operand is a structure to a pointer, then If the left operand is a structure to a pointer, then
the “structure indirection operator” (a hyphen the “structure indirection operator” (a hyphen followed immediately by a greater-than symbol) followed immediately by a greater-than symbol) will first de-reference the pointer and then access will first de-reference the pointer and then access the indicated element.the indicated element.
The code : The code : p->ptp->pt compiles as compiles as (*p).pt(*p).pt
Primitive and Utility FunctionsPrimitive and Utility Functions
Structure elements frequently change.Structure elements frequently change. Sloppy use of structures becomes a code Sloppy use of structures becomes a code
maintenance nightmare.maintenance nightmare. Primitive and Utility functions provide a localized Primitive and Utility functions provide a localized
interface to a structure’s elements.interface to a structure’s elements. ONLY the primitive function should ever directly ONLY the primitive function should ever directly
access the structure elements.access the structure elements. ONLY the utility functions should ever call the ONLY the utility functions should ever call the
primitive functions.primitive functions. The programmer should only use utility (and The programmer should only use utility (and
higher) functions.higher) functions.
Get()/Set() Primitive FunctionsGet()/Set() Primitive Functions
One Get()/Set() Pair for each structure One Get()/Set() Pair for each structure element.element.
Get() functions read the current value.Get() functions read the current value. Set() functions write a new value.Set() functions write a new value. Both return the final value.Both return the final value. Work best if structures passed by reference.Work best if structures passed by reference.
Get()/Set() list for PT3DGet()/Set() list for PT3D
int GetPT3D_pt(PT3D *p);
int SetPT3D_pt(PT3D *p, int v);
double GetPT3D_x(PT3D *p);
double SetPT3D_x(PT3D *p, double v);
double GetPT3D_y(PT3D *p);
double SetPT3D_y(PT3D *p, double v);
double GetPT3D_z(PT3D *p);
double SetPT3D_z(PT3D *p, double v);
Get()/Set() Primitive FunctionsGet()/Set() Primitive Functions
int GetPT3D_pt(PT3D *p){
if (NULL == p)return -1;
return p->pt;}
int SetPT3D_pt(PT3D *p, int v){
if (NULL == p)return -1;
p->pt = v;return GetPT3D_pt(p);
}
Naming convention:Naming convention:Get[STRUCT]_[element]Get[STRUCT]_[element]
element typeelement type
Set() calls the Get()Set() calls the Get()to return valueto return value
element nameelement name
NULLNULLcheckcheck
Utility Function - set all the point coordinates at once.Utility Function - set all the point coordinates at once.
PT3D NewPoint(int pt, double x, double y, double z)PT3D NewPoint(int pt, double x, double y, double z)
{{
PT3D temp;PT3D temp;
SetPT3D_pt(&temp, pt);SetPT3D_pt(&temp, pt);
SetPT3D_x(&temp, x);SetPT3D_x(&temp, x);
SetPT3D_y(&temp, y);SetPT3D_y(&temp, y);
SetPT3D_z(&temp, z);SetPT3D_z(&temp, z);
return temp;return temp;
}}
Utility Function - subtract two points (vector between points).Utility Function - subtract two points (vector between points).
PT3D SubtractPT3D(PT3D ptA, PT3D ptB)PT3D SubtractPT3D(PT3D ptA, PT3D ptB)
{{
PT3D temp;PT3D temp;
SetPT3D_pt(&temp, 0);SetPT3D_pt(&temp, 0);
SetPT3D_x(&temp, GetPT3D_x(&ptA) - GetPT3D_x(&ptB) );SetPT3D_x(&temp, GetPT3D_x(&ptA) - GetPT3D_x(&ptB) );
SetPT3D_y(&temp, GetPT3D_y(&ptA) - GetPT3D_y(&ptB));SetPT3D_y(&temp, GetPT3D_y(&ptA) - GetPT3D_y(&ptB));
SetPT3D_z(&temp, GetPT3D_z(&ptA) - GetPT3D_z(&ptB));SetPT3D_z(&temp, GetPT3D_z(&ptA) - GetPT3D_z(&ptB));
return temp;return temp;
}}
Utility Function - Distance between two pointsUtility Function - Distance between two points
double DistanceBetweenPT3D(PT3D ptA, PT3D ptB)double DistanceBetweenPT3D(PT3D ptA, PT3D ptB)
{{
double distance;double distance;
distance = LengthPT3D(SubtractPT3D(ptA, ptB));distance = LengthPT3D(SubtractPT3D(ptA, ptB));
return distance;return distance;
}}
Utility Function - Distance between two pointsUtility Function - Distance between two points
double LengthPT3D(PT3D ptA)double LengthPT3D(PT3D ptA)
{{
double length;double length;
int i;int i;
for (i = 0, length = 0.0; i < 3; i++)for (i = 0, length = 0.0; i < 3; i++)
length += pow(GetPT3D_dimensionN(&ptA, i),2);length += pow(GetPT3D_dimensionN(&ptA, i),2);
return sqrt(length);return sqrt(length);
}}
Utility Function - Get coordinate of a point based on indexUtility Function - Get coordinate of a point based on index
double GetPT3D_dimensionN(PT3D *p, int i)double GetPT3D_dimensionN(PT3D *p, int i){{
if (NULL == p)if (NULL == p)return -1;return -1;
switch (i)switch (i){{
case 0: return GetPT3D_x(p); break; case 0: return GetPT3D_x(p); break; case 1: return GetPT3D_y(p); break; case 1: return GetPT3D_y(p); break; case 2: return GetPT3D_z(p); break; case 2: return GetPT3D_z(p); break;
}}return -2;return -2;
}}
Simple main()Simple main()
#define PTS (5)#define PTS (5)
int main(void)int main(void){{
int i;int i;PT3D pt[PTS+1];PT3D pt[PTS+1];double theta;double theta;
for (i = 0; i <= PTS; i++)for (i = 0; i <= PTS; i++){{
theta = i * (2.0*PI/(double) PTS);theta = i * (2.0*PI/(double) PTS);pt[i] = NewPoint(i, cos(theta), sin(theta), 0.0);pt[i] = NewPoint(i, cos(theta), sin(theta), 0.0);fprintPT3D(stdout, pt[i]);fprintPT3D(stdout, pt[i]);
}}return 0;return 0;
}}
Utility function to print structure to a file.Utility function to print structure to a file.
void fprintPT3D(FILE *fp, PT3D pt)void fprintPT3D(FILE *fp, PT3D pt)
{{
int i;int i;
fprintf(fp, “%i”, GetPT3D_pt(&pt));fprintf(fp, “%i”, GetPT3D_pt(&pt));
for (i = 0; i <= 3; i++)for (i = 0; i <= 3; i++)
fprintf(fp, “, %f”, GetPT3D_dimensionN(&pt, i));fprintf(fp, “, %f”, GetPT3D_dimensionN(&pt, i));
fprintf(fp, “\n”);fprintf(fp, “\n”);
}}