Pointers (Part 2), Structures (Part 2), Unions

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 37

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's CS50; An introduction to the intellectual enterprises of
computer science and the art of programming, Harvard School of
Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of
New South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++
(2011), and 6.S096 Introduction to C and C++ (2013), MIT (Massachusetts
1
Institute of Technology) OpenCourseWare.
2

• Pointers [ Part 2 ]
• Passing an Array to a Function
• Functions returning Multiple Results
• Structures [ Part 2 ]
O • Defining members (variables, arrays,
u & pointers)
t • Accessing the Members (variables,

Outline l
i
arrays, & pointers)
n • Structures of Structures
e • Structures with Functions
• Unions
• Declaring a Union
• Defining & Accessing its Members
Pointers
[ Part 2 ]
Passing an
Array to a
Function
Passing a 1D Array to a Function: a
Copy
Example 1 Address b
0
0
1
&a[0]
2
// See the complete code in fig. 6.13 p.262-263 2 4
int a[ SIZE ] = { 0, 1, 2, 3, 4 }; 3
/* Pass an array to be modified in a function
6
4 8
Array by reference */
modifyArray( a, SIZE ); // Only the name of the array is passed
for ( i = 0; i < SIZE; i++ ) { Pass array name
printf( "%3d", a[ i ] ); is
} /* end for */ “Call by reference”

void modifyArray( int b[], int size )


02468 {
int j; /* counter */
for ( j = 0; j < size; j++ ) {
b[ j ] *= 2;
} /* end for */
} /* end function modifyArray */
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;
}
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>
}
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
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 ] )
{ Must be specified
for( int i = 0; i < 2; i++ )
for( int j = 0; j < 2; j++ )
printf( "%d\n", c[ i ][ j ] );
}
int main() {
int c[ 2 ][ 2 ]= { 5, 6, 2, 1};
Function( c );
return 0;
}
Pointers
[ Part 2 ]
Functions
Returning
Multiple Results
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.
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); a = 5 and b = 7
printf("a = %d and b = %d", a, b);
Nothing has happened
return 0;
}
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); a = 7 and b = 5
printf("a = %d and b = %d", a, b);
return 0;
}
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 ];
}
}
}
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;
}
Structures
[ Part 2 ]
Declaring Structures
Create a structure for an employee, storing his/her name, gender, .., and salary.

Structure Name

struct employee { struct card {


char firstName[ 20 ]; char * face;
char lastName[ 20 ]; char * suit;
int age; };
char gender;
double hourlySalary;
};
Structure Members
Must end with semicolon

Structures may contain variables of many different data types ..


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 card { struct {


char *face; char *face;
Or ..
char *suit; char *suit;
}; } aCard, deck[ 52 ], *cardPtr;
..
struct card aCard; // define a variable of structure
struct card deck[ 52 ];
// define array of structure
struct card *cardPtr;
// define a pointer to structure
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
18
person. ...
Person p1, p[50], *ptr;
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
Accessing the Members of a Pointer to a
Structure

..
Card * cardPtr; /* Pointer */
..
(*cardPtr).face = "Three";
(*cardPtr).suit = "Hearts";
Or
cardPtr->face = "Three";
cardPtr->suit = "Hearts";

printf( "%s", cardPtr->suit ); // displays Hearts


printf( "%s", (*cardPtr).suit ); // displays Hearts
Accessing the Members of an Array of
Structures

..
Card deck[52];
..

deck[2].face = "Three";
deck[2].suit = "Hearts";
One element of an array of structs,
.. which is a struct ..
for (int i = 0; I < 52;i++ )
printf( "%s%s", deck[ i ].face, deck[ i ].suit );
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;
}
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

}
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;
Self-Referential Structures

struct employee {
char firstName[ 20 ];
char lastName[ 20 ];
int age;
char gender;
Can’t contain an instance of itself
double hourlySalary;
struct employee person; /* ERROR */
struct employee *ePtr; /* Pointer */

}; Can include a pointer to the same structure


25
type
“self-referential structure”
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.
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;
}
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 );
}
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).
Unions
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.
Declaring & Initializing Unions

union number { Tag


int x;
double y;
} n1, n2, *Pn; 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 ); int: 100

value.y = 100.0; // put a double into the same union


printf("double: %f\n", value.y ); double: 100.000000
} // end main
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.
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
Unions .. An Example
C 1
10 2
union Data { 20.5
p 3
int i; r 4
float f; o
char str[ 20 ]; 5
g
}; \0 6
int main( ) { .
.
union Data data; .
data.i = 10; .
data.f = 20.5; 20
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
Unions .. An Example
union Data {
int i;
float f;
char str[ 20 ]; data.i : 10
}; data.f : 20.500000
int main( ) { data.str : C Programming
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);
}
Thanks! .. Questions?

37

You might also like