950 likes | 961 Views
Fundamentals of C and C++ Programming Simple data structures Pointers. Arrays Structures Unions. Simple Data Structures. Simple Data Structures. It would be limiting to have to express all data as variables. It would be desirable to be able to group data into sets of related data.
E N D
Fundamentals of C and C++ ProgrammingSimple data structuresPointers
Arrays Structures Unions Simple Data Structures
Simple Data Structures • It would be limiting to have to express all data as variables. • It would be desirable to be able to group data into sets of related data. • This can be done two main ways: • arrays (all data of the same type) • structures (data may be of different types).
Type Definitions • Special data types designed by the programmer can be defined through the typedef keyword. • For example, if we want to define a data type that is to be defined only once and then used thereafter: typedef unsigned long int Myvar
Type Definitions • So, Myvar can now be used to indicate an unsigned long int wherever used. Myvar n; is the same as: unsigned long int n; • But it can be used for far more. (later)
Arrays • Left-most symbol indicates the name of the array. This is common for all its elements. • Individual data identified by distance from first one in array. • Within square brackets is the cell number (how many cells away from the first one). • Individual cells can be used as regular variables.
Arrays For array c: c[0] -45 c[1] 6 c[2] 0 c[3] 72 c[4] 1543 c[5] -89 c[6] 0 c[7] 62 c[8] -3
Declaring Arrays • The declaration allows the compiler to set aside sufficient contiguous memory for the size of array • The type of data to be stored must be identified so that sufficient space is allocated. • Arrays allocated statically - remain the same size throughout program execution.
Declaring Arrays int c[12]; float a[100]; char b[15]; • Can be automatic or external. • Size typically done through a macro. #define SIZE 10
Initializing Arrays • Not automatically initialized. Can be initialized during declaration or within the program in a loop. int n[10] = {32,27,64,18,95,14,90,70,60}; • If more elements than initialized, others = 0. • If less elements than initialized - error. int n[] = {32,27,64,18,95,14,90,70,60,37};
Passing Arrays to Functions • Arrays passed by reference - actual variable address passed. The called function can modify the original array’s values. • Pass name without brackets. • Include the size of the array as a passed value. • Function header and prototype must indicate that an array is being passed.
Passing Arrays to Functions #define SIZE 5 void function1(int [],int); void function2(int); main() { int a[] = {0, 1, 2, 3, 4}; function1(a,SIZE); function2(a[3]); }
Multi-dimension Arrays • Arrays can have an arbitrary number of dimensions. • Indicated by multiple bracket pairs. int a[5][10]; int b[10][12][20]; • Can be called in same way as vector arrays. • First bracket is the row script • Second is the column script.
Initializing Multi-dim. Arrays • Initialization by row in braces. • First brace equates to first row, 2nd to 2nd,. int c[2][2] = {{1,2} {3,4}}; • Initializes b[0][0]=1, b[0][1]=2, b[1][0]=3, and b[1][1]=4. • But what if int c[2][2] = {{1} {3,4}}; • Initializes b[0][0]=1, b[0][1]=0 , b[1][0]=3, and b[1][1]=4.
Arrays and Strings • Strings are in reality arrays of characters • Each element contains one character. • Each cell is one byte in size. • More about strings and string operations later.
Structures • A collection of related, but dissimilar variables under one name. • Provides great flexibility that an array does not. • Used to define records to be stored in files. • Also used to form dynamic data types such as linked lists, linked stacks and linked queues.
Structure Definitions • Declared as follows: struct planet { char *name; int nummoons; double dist_from_sun; float dist_from_earth; }; • This creates a definition of the structure. • planet is the structure tag.
Structures Components • The variables are called members. • They can be accessed individually using: • The structure member operator (also called the dot operator). • The structure pointer operator (also called the arrow operator). • See Figure 10.2, page 400 of textbook.
Structure Operators • The dot operator accesses the contents of the member using the member name and the structure variable name. planet.nummoons directly accesses the contents of the member nummoons • Can be used as a regular integer variable.
Structure Operators • The arrow operator accesses the contents of the member using a pointer to the structure variable and the member name. planet_ptr->nummoons directly points to the contents of the member nummoons • equal to (*planet_ptr).nummoons
Structure Variables • The struct keyword defines a “model” of the desired structure. • It is not a real variable per se. • A real variable is created by creating an instance of the structure model. • Also referred to as “instantiating”.
Structure Variables • To make instances of the definition: • Instance name(s) can be added after the definition. • Can be defined as a data type to be instantiated separately. • The struct keyword can be used along with the tag to instantiate. • See examples next.
Structure Variables • Instances added after the definition: struct planet { char *name; int nummoons; double dist_from_sun; float dist_from_earth; } earth, mars, solar[9], *ptr; • solar[9] is an array of 9 structures of type planet. ptr is a pointer to a planet type.
Structure Variables • The tag is optional. The following code is equivalent to the one in the last slide: struct { char *name; int nummoons; double dist_from_sun; float dist_from_earth; } earth, mars, solar[9], *ptr; • Only way to instantiate is in the definition.
Structure Variables • Defined as a datatype: typedef struct planet Planet; Planet earth, mars; Planet *ptr; Planet solar[9]; • This assumes that the structure definition is as before.
Structure Variables • Can also be done directly in the definition: typedef struct planet { char *name; int nummoons; double dist_from_sun; float dist_from_earth; } Planet; • The planet tagis not necessary in this case.
Structure Variables • The struct keyword can also be used to instantiate. struct planet { char *name; int nummoons; double dist_from_sun; float dist_from_earth; }; struct planet earth;
Initializing Structure Members • Like in arrays. • Use values inside braces. • Only when variable being instantiated. struct planet earth = {earth,1,1.0e+6,0} • If less values than members, then only the first few are initialized. Others = 0. • Must be constant values or expressions.
Structures and Functions • Structures can be passed to functions as: • Individual structure members. • An entire structure variable. • Pointer to a structure variable. • Passed by value if the individual structure member or the entire structure is passed. • Passed by reference if a pointer to the structure is passed.
Structures • Arrays can be assigned to a structure member. • There can be arrays of structures. • Structure members can be other structures. • Structure members can be self-referencing structures - pointers that point to similar structures as itself.
Unions • Same as structures, except members share same storage space. • Saves space when some members are never used at the same time. • Space for a member must be large enough to accommodate the largest of the data types to be stored in that member.
Unions • Unions are declared and defined in a way similar to structures. • The keyword union replaces the keyword struct. • Not highly recommended except when memory management is critical.
Enumeration Constants • Allows a set of integer constants to be represented by identifiers. • Symbolic constants whose value can be set automatically. • Values start with 0 (unless otherwise noted by programmer) and are incremented by 1. • Uses the enum keyword for definition.
Enumeration Example #include <stdio.h> enum months {JAN=1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, ACT, NOV, DEC} main() { enum months month; char *monthName[] = {“”, “January”,..}; for(month=JAN;month<=DEC;month++) printf(……….monthName[month]; }
Pointer Variables • Conventional variables contain values. • Pointer variable contains memory address of variable that contains values (or pointers) • Allows call by reference. • Permits creation of dynamic data structures. • Permits dynamic allocation of memory. • Difficult to understand and use.
Pointer Variables • Conventional variable names directly reference a value. • Pointer variables indirectly reference a value • Referencing a value through a pointer variable is called indirection. • Pointer variables = pointers
Declaration of Pointer Variables • Pointers must be declared like regular variables. • It must be stated which type of variable they point to. • Declarations use * to indicate “pointerhood” int *ptr; • pointer ptr points to an integer variable.
Pointer Variables • Pointers should be initialized. • The * does not distribute. • Can be set to NULL or to 0, but NULL is preferred. • NULL is a symbolic constant defined in <stdio.h> • Pointers assigned a value of 0 actually have the value 0 and not an address.
Address-of Pointer Operator • Address-of operator (&) is a unary operator returning the address of its operand. • The basic operator used to assign values to pointers. int y = 5; int *ptr; ptr = &y; • ptr points to y (contains its address).
Indirection Pointer Operator • Indirection operator (*), or dereferencing operator is also unary and returns the value of the variable pointed at by the pointer. • In the previous example: y = 5 *ptr = 5 • Not to be confused with the declaration operator - very confusing!!!.
Pointer Example main() { int a; int *aptr; a = 7; aptr = &a; printf(“The address of a =%d“,&a); printf(“The value of aptr =%d“, aptr); printf(“The value of a = %d“, *aptr); }
Call by Reference with Pointers • By passing a variable’s address to a function, we give that function the ability to modify the value of the original value. • This is a simulation of call by reference.
Call by Value - Example void value_funct1(int); main() { int number = 5; printf(“Original value =“, number); value_funct(number); printf(“New value =“, number); } void value_funct(int n); { n = n * n; }
Call by Value - Example Original value = 5 New value = 5 • The call to function value_funct did not change the original variable number in main().
Call by Reference - Example void value_funct2(int *); main() { int number = 5; printf(“Original value =“, number); value_funct(&number); printf(“New value =“, number); } void value_funct(int *nptr); { (*nptr) = (*nptr) * (*nptr); }
Call by Reference - Example Original value = 5 New value = 25 • The call to function value_funct changed the original variable number in main(). • A similar effect can be obtained by value_funct returning a value to main()
Functions Returning Pointers • Functions can also return pointers to variables. int* function1(int, int); is the prototype for a function that returns a pointer to an integer variable. • Is easily done by simply returning the value of a pointer variable - an address.
The const and Pointer Passing • The const qualifier tells the compiler that the variable following it is not to be changed by any program statements. • Provides a measure of security when passing addresses of variables whose values are not to be modified (for example, arrays). • When passing pointers, 4 possibilities exist:
Pointer Passing • Non-constant pointer to non-constant data • Declaration does not include const in any way. • Data can be modified through the pointer. • Pointer can be modified to point to other data. • Highest level of data access to called function. • This is what we have been doing up to now.