Programming Pointers, Structures, Unions: Lecture Details and Examples

cs112 level 1 programming languages 1 n.w
1 / 37
Embed
Share

Explore pointers, structures, and unions in programming through examples and explanations in this comprehensive lecture series based on courses from Harvard, UNSW, and MIT.

  • Programming
  • Pointers
  • Structures
  • Unions
  • Lecture

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. CS112 Level 1 Programming Languages 1 Lecture 6 Pointers [ Part 2 ], Structures [ Part 2 ], Unions Course & Lectures are based on their counterparts in the following courses: o Harvard University'sCS50; An introduction to the intellectual enterprises of computer science and the art of programming, Harvard School of Engineering and Applied Sciences. o UNSW'sCS1: Higher Computing, by Richard Buckland The University of New South Wales. o MIT's6.087 Practical Programming in C (2010), 6.096 Introduction to C++ (2011), and 6.S096 Introduction to C and C++ (2013), MIT (Massachusetts Institute of Technology) OpenCourseWare. 1

  2. 2 Pointers [ Part 2 ] Passing an Array to a Function Functions returning Multiple Results Structures [ Part 2 ] Defining members (variables, arrays, & pointers) Accessing the Members (variables, arrays, & pointers) Structures of Structures Structures with Functions Unions Declaring a Union Defining & Accessing its Members O u t l i n e Outline

  3. Pointers [ Part 2 ] Passing an Array to a Function

  4. Passing a 1D Array to a Function: Example 1 a Copy Address 0 0 2 4 6 8 b 1 &a[0] // See the complete code in fig. 6.13 p.262-263 int a[ SIZE ] = { 0, 1, 2, 3, 4 }; /* Pass an array to be modified in a function Array by reference */ modifyArray( a, SIZE ); // Only the name of the array is passed for ( i = 0; i < SIZE; i++ ) { printf( "%3d", a[ i ] ); } /* end for */ 2 3 4 Pass array name is Call by reference void modifyArray( int b[], int size ) { int j; /* counter */ for ( j = 0; j < size; j++ ) { b[ j ] *= 2; } /* end for */ } /* end function modifyArray */ 0 2 4 6 8

  5. Passing a 1D Array to a Function: Example 2 #include <stdio.h> void IncreamentBy5( int * ); int main() { int c[ ] = { 23, 55, 22, 3, 40, 18 }; IncreamentBy5( c ); for ( int i = 0; i < 6; i++) printf("%d\t", c[ i ] ); return 0; } void IncreamentBy5( int *a ) // can be written as int a[ ] { for( int i = 0; i < 6; i++ ) a[i] +=5; }

  6. Converting a String to UpperCase using a Non-Constant Pointer to Non-Constant data .. int main( void ) { char string[ ] = "cHaRaCters"; printf("Before conversion, the string is: %s", string); convertToUpperCase( string ); printf("\nAfter conversion, the string is: %s\n", string); } void convertToUpperCase( char *sPtr ) { while ( *sPtr != '\0' ) { *sPtr = toupper( *sPtr ); ++sPtr; } } <ctype.h>

  7. Printing a String one character at a time using a Non-Constant Pointer to Constant Data .. int main( void ) { char string[ ] = "print the characters of a string"; // initialize the char array printCharacters( string ); puts( "" ); } // end main Can t change the array values void printCharacters( const char *sPtr ) { // loop through entire string for ( ; *sPtr != '\0'; ++sPtr ) // no initialization { printf( "%c", *sPtr ); } // end for } // end function

  8. Passing a 2D Array to a Function To pass a two-dimensional array to a function as an argument, the starting address of the memory area reserved is passed as in a one dimensional array. void Function( int c[ ][ 2 ] ) { for( int i = 0; i < 2; i++ ) for( int j = 0; j < 2; j++ ) } int main() { int c[ 2 ][ 2 ]= { 5, 6, 2, 1}; Function( c ); return 0; } Must be specified printf( "%d\n", c[ i ][ j ] );

  9. Pointers [ Part 2 ] Functions Returning Multiple Results

  10. Functions Returning Multiple Results o This ability to indirectly access a variable is the key to writing functions that return multiple results. o We declare such functions using pointer variables as their formal parameters. o From the calling function, instead of passing the values of the variables as actual arguments, we pass the addresses of the variables. o This will allow the function to indirectly manipulate the variables of the calling function thus achieving the desired effect.

  11. Returning Two Numbers .. void swap (int x, int y) { int temp; temp = x; x = y; y = temp; } int main() { int a = 5, b = 7; swap( a, b); printf("a = %d and b = %d", a, b); return 0; } a = 5 and b = 7 Nothing has happened

  12. Returning Two Numbers .. void swap (int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; } int main() { int a = 5, b = 7; swap( &a, &b); printf("a = %d and b = %d", a, b); return 0; } a = 7 and b = 5

  13. Returning the Results in an Array .. Write a C function that sums the elements of a Matrix of integer values, row by row, in an another array. void sum( int s[ ][ 5 ] , int size, int a[ ] ) { int i, j; for( i = 0; i < size; i++ ) { a[ i ]=0; for( j = 0; j < 5; j++ ) { a[ i ] += s[ i ][ j ]; } } }

  14. Returning Multiple Results .. an Example Write a C function that receives a circle s radius, and returns its area and circumference. Call this function from main. #include <stdio.h> void area_circum ( double radius, double *area, double *circum ); int main ( void ) { double radius, area, circum; printf ("Enter the radius of the circle: "); scanf ("%lf", &radius); area_circum ( radius, &area, &circum ); printf ("The area is %f & the circumference is %f\n", area, circum); return 0; } void area_circum ( double radius, double *area, double *circum ) { *area = 3.14 * radius * radius; *circum = 2 * 3.14 * radius; }

  15. Structures [ Part 2 ]

  16. Declaring Structures Create a structure for an employee, storing his/her name, gender, .., and salary. Structure Name struct card { }; struct employee { char firstName[ 20 ]; char lastName[ 20 ]; int age; char gender; double hourlySalary; }; char * face; char * suit; Structure Members Must end with semicolon Structures may contain variables of many different data types ..

  17. Declaring Variables of Structure Types Structure definitions do not reserve any space in memory. To define variables: The Structure name can be omitted, as in this example: struct { } aCard, deck[ 52 ], *cardPtr; struct card { }; .. struct card aCard; struct card deck[ 52 ]; struct card *cardPtr; char *face; char *suit; char *face; char *suit; Or .. // define a variable of structure // define array of structure // define a pointer to structure

  18. typedef typedef provides a mechanism for creating synonyms (or aliases) for previously defined data types. Can be omitted .. typedef struct person { char name[50]; int cit_no; float salary; } Person; So, Person can now be used to declare variables of the type struct person. ... Person p1, p[50], *ptr; 18

  19. Accessing the Members of a Structure typedef struct { char *face; char *suit; } Card; int main() { .. Card aCard; .. aCard.face = "Three"; aCard.suit = "Hearts"; printf( "%s", aCard.face ); /* displays Three */ Accessing the members

  20. Accessing the Members of a Pointer to a Structure .. Card * cardPtr; .. (*cardPtr).face = "Three"; (*cardPtr).suit = "Hearts"; Or cardPtr->face = "Three"; cardPtr->suit = "Hearts"; /* Pointer */ printf( "%s", cardPtr->suit ); // displays Hearts printf( "%s", (*cardPtr).suit ); // displays Hearts

  21. Accessing the Members of an Array of Structures .. Card deck[52]; .. deck[2].face = "Three"; deck[2].suit = "Hearts"; for (int i = 0; I < 52;i++ ) printf( "%s%s", deck[ i ].face, deck[ i ].suit ); One element of an array of structs, which is a struct .. ..

  22. An Example int main( ) { } status record[ 10 ]; int i; for ( i = 0; i < 10; i++ ) { printf("Enter student name & his (her) percentage"); record[ i ].id = i; scanf ("%s %f ", record[ i ].name, &record[ i ].percentage); } for ( i = 0; i < 10; i++ ) { printf("The Record of STUDENT: %d \n", i + 1); printf("Id is: %d \n", record[ i ].id ); printf("Name is: %s \n", record[ i ].name ); printf("Percentage is: %f\n", record[ i ].percentage); } return 0;

  23. Structures of Structures int main( ) { } n1.real = 3.5; n1.c1.imag_value = 5; n1.c1.real_value = 0.65; .. n2.real = 6.4; n2.c1.imag_value = 9; n2.c1.real_value = 4.95; .. return 0; 23

  24. Structures of Structures typedef struct student_college { int college_id; char college_name[ 50 ]; } Stud_col; typedef struct student { int id; char name[ 20 ]; float grades[ 10 ]; Stud_col clg_data; } stu_data;

  25. Self-Referential Structures struct employee { char firstName[ 20 ]; char lastName[ 20 ]; int age; char gender; double hourlySalary; struct employee person; struct employee *ePtr; Can t contain an instance of itself /* ERROR */ /* Pointer */ Can include a pointer to the same structure type self-referential structure }; 25

  26. Using Structures with Functions .. Structures may be passed to functions: by passing individual structure members, by passing an entire structure, or .. by passing a pointer to a structure. When structures or individual structure members are passed to a function, they are passed by value.

  27. Using Structures with Functions .. typedef struct student { int id; char name[ 20 ]; float perc; } Student; void Assign ( Student *record ) { record -> id = 12; record -> name = "Mohamed"; record -> perc = 85.6; }

  28. Using Structures with Functions .. void Out( Student record ) { printf( "Id is: %d \n", record.id ); printf( "Name is: %s \n", record.name ); printf( "Percentage is: %f \n", record.perc ); } void main() { Student S; Assign( &S ); Out( S ); }

  29. Using Structures with Functions .. Note that: An array could be passed by value by creating a structure with the array as a member. Structures are passed by value, so the array is passed by value. Passing structures by reference is more efficient than passing structures by value (which requires the entire structure to be copied).

  30. Unions

  31. Unions A union is a derived data type like a structure with members that share the same storage space. The number of bytes used to store a union must be at least enough to hold the largest member. Only one member, and thus one data type, can be referenced at a time.

  32. Declaring & Initializing Unions Tag union number { } n1, n2, *Pn; int x; double y; Variables int main( void ) { union number value; // define union variable value.x = 100; // put an integer into the union printf("int: %d\n", value.x ); value.y = 100.0; // put a double into the same union printf("double: %f\n", value.y ); } // end main int: 100 double: 100.000000

  33. Operations that can be Performed on Unions The operations that can be performed on a union are the following: Assigning a union to another union of the same type, Taking the address (&) of a union variable, and .. Accessing union members using the structure member operator and the structure pointer operator. Unions may not be compared using operators == and != for the same reasons that structures cannot be compared.

  34. Unions .. An Example union Data { } ; int i; float f; char str[ 20 ]; int main( ) { } union Data data; // declaring data printf( "Memory size of data: %d\n", sizeof( data ) ); Memory size of data: 20

  35. Unions .. An Example 1 C 10 20.5 p r o g \0 2 union Data { int i; float f; char str[ 20 ]; } ; int main( ) { union Data data; data.i = 10; data.f = 20.5; data.str = "C Prog"; printf( "data.i : %d\n", data.i); printf( "data.f : %f\n", data.f); printf( "data.str : %s\n", data.str); } data.i : 1917853763 data.f : 4122360580327794860452759994368.00000 data.str : C Prog 3 4 5 6 . . . . 20

  36. Unions .. An Example union Data { int i; float f; char str[ 20 ]; } ; int main( ) { union Data data; data.i = 10; printf( "data.i : %d\n", data.i); data.f = 20.5; printf( "data.f : %f\n", data.f); data.str = "C Prog"; printf( "data.str : %s\n", data.str); } data.i : 10 data.f : 20.500000 data.str : C Programming

  37. Thanks! .. Questions? 37

Related


More Related Content