Lecture Notes: C Programming
Arrays, Strings, Pointers, Structs, and Unions
Dr. Kim Dinh Thai (VNU-IS)
November 5, 2025
Contents
I Arrays and Strings 3
1 One-Dimensional Arrays (1D Arrays) 3
1.1 Declaration and Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Accessing Array Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 Two-Dimensional Arrays (2D Arrays) 4
2.1 Declaration and Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2 Accessing 2D Array Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3 Strings (Character Arrays) 5
3.1 Declaration and Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.2 Reading and Writing Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.3 String Functions (string.h) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
II Pointers 6
4 Pointer Basics 7
4.1 Address (&) and Dereference (*) Operators . . . . . . . . . . . . . . . . . . . . . 7
4.2 Declaring and Using Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
5 Pointers and Arrays 9
6 Pointers and Functions 9
6.1 Pass by Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
6.2 Pass by Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
7 Other Pointer Topics 11
III Structures and Unions 12
8 Structures (Struct) 12
8.1 Declaration and Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
8.2 Accessing Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
8.3 Structures and Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
8.4 Arrays of Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1
8.5 Nested Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
9 Unions 15
9.1 Declaration and Use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
9.2 Difference between Struct and Union . . . . . . . . . . . . . . . . . . . . . . . . . 16
2
Part I
Arrays and Strings
1 One-Dimensional Arrays (1D Arrays)
An array is a collection of elements of the same data type, stored in contiguous memory locations.
We can access each element through a common name (the array name) and an index.
1.1 Declaration and Initialization
Declaring an array requires a data type, array name, and size (number of elements). Array
indices in C always start from 0.
Example
1 // Declare an integer array of 5 elements
2 // This reserves space in memory for 5 integers .
3 int scores [5];
4
5 // Initialize array at declaration
6 int initialScores [5] = {10 , 8 , 9 , 7 , 10};
7
8 // Size can be omitted if initialized immediately
9 // The compiler automatically calculates the size .
10 int autoSizeScores [] = {10 , 8 , 9}; // Compiler understands size is 3
Programming Exercises
1. Write a program to store 10 elements in an array and print them.
2. Write a program to insert an element at a specific position in an array.
3. Write a program to delete an element from a specific position in an array.
4. Write a program to copy the elements of one array into a new array.
5. Write a program to reverse the elements of an array (without using a secondary array).
1.2 Accessing Array Elements
We use the subscript operator ‘[]‘ with an index to access elements. ‘scores[0]‘ is the first element,
‘scores[4]‘ is the last element (in a 5-element array).
Example
1 int scores [5] = {10 , 8 , 9 , 7 , 10};
2
3 // Access the first element ( index 0)
4 int firstScore = scores [0]; // firstScore is 10
5
6 // Assign a new value to the third element ( index 2)
7 scores [2] = 5;
8
9 // Loop through the array to print elements
10 // Array indices go from 0 to ( size - 1)
11 for ( int i = 0; i < 5; i ++) {
3
12 printf ( " Element % d : % d \ n " , i , scores [ i ]) ;
13 }
Programming Exercises
1. Write a program to search for an element in an array. If found, print its position (index).
2. Write a program to calculate the sum of all elements in an integer array.
3. Write a program to calculate the average value of the elements in an array.
4. Write a program to count the number of even and odd numbers in an array.
5. Write a program to print all numbers in an array that are greater than the array’s average
value.
2 Two-Dimensional Arrays (2D Arrays)
A 2D array can be visualized as a table or matrix with rows and columns. Essentially, it is an
"array of arrays."
2.1 Declaration and Initialization
Example
1 // Declare a 3 x4 matrix (3 rows , 4 columns )
2 int matrix [3][4];
3
4 // Initialize a 2 x3 matrix
5 int matrixA [2][3] = {
6 {1 , 2 , 3} , // Row 0
7 {4 , 5 , 6} // Row 1
8 };
Programming Exercises
1. Write a program to add two 3x3 matrices and store the result in a third matrix.
2. Write a program to multiply two 3x3 matrices.
3. Write a program to find the transpose of a 3x3 matrix.
4. Write a program to calculate the sum of all elements in a matrix.
5. Write a program to calculate the sum of the elements on the main diagonal of a square
matrix.
2.2 Accessing 2D Array Elements
We need two indices: the row index and the column index. Nested loops are required to traverse
a 2D array.
4
Example
1 // Assign value 99 to element at row 1 , col 2
2 matrixA [1][2] = 99;
3
4 // Loop through the 2 x3 matrix
5 for ( int i = 0; i < 2; i ++) { // Outer loop for rows
6 for ( int j = 0; j < 3; j ++) { // Inner loop for columns
7 printf ( " % d " , matrixA [ i ][ j ]) ;
8 }
9 printf ( " \ n " ) ; // New line after each row
10 }
Programming Exercises
1. Write a program to calculate the sum of elements for each row in a 3x4 matrix.
2. Write a program to calculate the sum of elements for each column in a 3x4 matrix.
3. Write a program to calculate the sum of elements above the main diagonal.
4. Write a program to calculate the sum of elements below the main diagonal.
5. Write a program to print the elements on the main diagonal and the anti-diagonal.
3 Strings (Character Arrays)
In C, a string is not a basic data type. It is represented as a one-dimensional array of characters
(‘char‘) terminated by a special character called the NULL character (’\0’).
3.1 Declaration and Initialization
Example
1 // Declare a string that can hold 19 chars + 1 NULL char
2 char name [20];
3
4 // Initialize string ( compiler adds ’\0 ’ automatically )
5 char greeting [] = " Hello " ;
6
7 // Equivalent initialization ( must add ’\0 ’ manually )
8 char greeting2 [] = { ’H ’ , ’e ’ , ’l ’ , ’l ’ , ’o ’ , ’ \0 ’ };
Programming Exercises
1. Write a program to convert an input string to uppercase (without using ‘strupr‘).
2. Write a program to concatenate two strings (without using ‘strcat‘).
3. Write a program to copy one string to another (without using ‘strcpy‘).
4. Write a program to toggle the case of each character in a string (e.g., ’aBc’ -> ’AbC’).
5. Write a program to delete a user-specified word from a string.
5
3.2 Reading and Writing Strings
• scanf(): Reads a string but stops at the first whitespace.
• gets(): Reads an entire line (including whitespace) but is unsafe (can cause buffer over-
flow).
• printf(): Prints a string to the console using the ‘
• puts(): Prints a string to the console and automatically adds a newline character.
Programming Exercises
1. Write a program to count the number of vowels, consonants, and spaces in a string.
2. Write a program to input a word and print it in a triangle pattern (e.g., ’WORD’ -> W,
WO, WOR, WORD...).
3. Write a program to count the occurrences of a specific character in a string.
4. Write a program to find the longest word in a sentence.
5. Write a program to change each character to the next character in the alphabet (e.g., ’abc’
-> ’bcd’).
3.3 String Functions (string.h)
To work with strings, we should include the ‘string.h‘ library.
• strlen(s): Returns the length of the string (not counting ’\0’).
• strcpy(dest, src): Copies the string ‘src‘ into ‘dest‘.
• strcat(dest, src): Appends the string ‘src‘ to the end of ‘dest‘.
• strcmp(s1, s2): Compares two strings. Returns 0 if equal, < 0 if s1 < s2, > 0 if s1 > s2.
Programming Exercises
1. Write a program that uses ‘strlen()‘ to find and print the length of a string input by the
user.
2. Write a program that asks the user for a first name and last name, then uses ‘strcpy()‘ to
copy the first name and ‘strcat()‘ to append the last name to create a full name.
3. Write a program that asks for 2 strings and uses ‘strcmp()‘ to report which string comes
first alphabetically.
4. Write a program to check if a string is a palindrome (e.g., "MADAM"). (Hint: copy the
string, reverse the copy using ‘strrev‘, then compare).
5. Write a program that uses ‘strlwr()‘ and ‘strupr()‘ to print the lowercase and uppercase
versions of a string.
Part II
Pointers
6
4 Pointer Basics
A pointer is a special variable used to store the memory address of another variable.
4.1 Address (&) and Dereference (*) Operators
• Operator & (Address-of ): Returns the memory address of a variable.
• Operator * (Dereference/Indirection): Returns the value stored at the address the
pointer is pointing to.
Code Analysis Exercises
Find errors or predict the output of the following code snippets:
1.1 int main () {
2 int A [3]={3 ,6 ,9}; int i ; int * p ; p = A ;
3 for ( i =0; i <3; i ++)
4 printf ( " % d % d % d " , p [ i ] , *( p + i ) , i [ p ]) ;
5 return 0;
6 }
7
1 int main () {
2 int A [3]={3 ,6 ,9}; int i ; int * p ; p = A ;
3 printf ( " % d " , * p ) ; p = p +1;
4 printf ( " % d " , * p ) ; p = p +1;
5 printf ( " % d " , * p ) ;
6 return 0;
7 }
8
3.
2.1 int main () {
2 int A [3]={3 ,6 ,9};
3 printf ( " \ n % d " , * A +2) ;
4 printf ( " \ n % d " , *( A +2) ) ;
5 return 0;
6 }
7
1 int main () {
2 int A [3]={3 ,6 ,9};
3 printf ( " % d " , * A ) ;
4 A = A +1; // Error ?
5 printf ( " % d " , * A ) ;
6 return 0;
7 }
8
5.
4.1 int main () {
2 int const x =25;
3 int * p ;
4 p =& x ; // Warning / Error ?
5 printf ( " % d " , * p ) ;
6 return 0;
7 }
8
7
4.2 Declaring and Using Pointers
Example
1 int var = 10; // Normal variable
2 int * ptr ; // Declare an int pointer ( will point to an int )
3
4 // Assign the address of ’ var ’ to ’ ptr ’
5 ptr = & var ;
6
7 // Using the pointer
8 printf ( " Address of var ( using & var ) : % p \ n " , ( void *) & var ) ;
9 printf ( " Address of var ( using ptr ) : % p \ n " , ( void *) ptr ) ;
10 printf ( " Value of var ( using var ) : % d \ n " , var ) ;
11 printf ( " Value of var ( using * ptr ) : % d \ n " , * ptr ) ; // Dereference
12
13 // Change ’ var ’s value via the pointer
14 * ptr = 20; // This is equivalent to : var = 20
15 printf ( " New value of var : % d \ n " , var ) ; // Will print 20
Code Analysis Exercises
Find errors or predict the output of the following code snippets:
1.1 int main () {
2 float A []={1.4 , 5.8 , 2.3};
3 float *p , * q ; int size ;
4 p =& A [2]; q =& A [0];
5 size = p - q ; // What is size ?
6 printf ( " % d " , size ) ;
7 return 0;
8 }
9
1 int main () {
2 int A []={4 , 8 , 3};
3 int B []={99 , 66 , 33};
4 int *p , * q ;
5 p =& A [2]; q =& B [2];
6 q = p ; // Is this valid ?
7 printf ( " % d " , * q ) ;
8 return 0;
9 }
10
3.
2.1 int main () {
2 int x =5; int * p ; p =& x ;
3 * p = * p + 1;
4 printf ( " % d " , * p ) ;
5 return 0;
6 }
7
1 int main () {
2 int x =5; int * p = & x ;
3 int ** pp = & p ;
4 printf ( " % d " , ** pp ) ; // Double dereference
5 return 0;
6 }
7
8
5.
4.1 int main () {
2 char str [] = " Hello " ;
3 char * s = str ;
4 printf ( " % c " , * s ) ; // Prints ’H ’
5 s ++; // Move pointer to next character
6 printf ( " % c " , * s ) ; // Prints ’e ’
7 return 0;
8 }
9
5 Pointers and Arrays
The name of an array is a constant pointer to the first element of the array.
• ‘arr‘ is equivalent to ‘&arr[0]‘.
• ‘*(arr + i)‘ is equivalent to ‘arr[i]‘.
• ‘(arr + i)‘ is the address of the element ‘arr[i]‘.
Programming Exercises
1. Write a function to sort an array in descending order. The function should accept a pointer
to the array and the array size.
2. Predict the output:
1 int main () {
2 int A []={3 ,6 ,9}; int i ; int * p = A ;
3 for ( i =0; i <3; i ++)
4 printf ( " % d " , *( p + i ) ) ;
5 return 0;
6 }
7
3. Predict the output:
1 int main () {
2 int A []={3 ,6 ,9}; int i ; int * p = A ;
3 for ( i =0; i <3; i ++)
4 printf ( " % d " , p [ i ]) ;
5 return 0;
6 }
7
4. Predict the output:
1 int main () {
2 int A []={3 ,6 ,9}; int i ; int * p = A ;
3 for ( i =0; i <3; i ++)
4 printf ( " % d " , i [ p ]) ; // Is this valid C ?
5 return 0;
6 }
7
5. Write a C program to copy one array into another using pointers.
6 Pointers and Functions
This is one of the most powerful uses of pointers, allowing a function to change the value of the
original variable outside the function.
9
6.1 Pass by Value
By default, C passes arguments to functions by value. The function receives a copy of the value.
Any changes inside the function do not affect the original variable.
Programming Exercises
1. Write a function to compare two strings by passing ‘char*‘ pointers. The function should
return 1 if identical, 0 otherwise.
2. Predict the output (Pass by Value):
1 void test ( int x ) { x = x +1; printf ( " % d " ,x ) ; }
2 int main () {
3 int x =5;
4 test ( x ) ;
5 printf ( " % d " ,x ) ; // What is the final value of x ?
6 return 0;
7 }
8
3. Predict the output (Global vs. Local):
1 int x =25; // Global variable
2 void test ( int x ) { x = x +1; printf ( " % d " ,x ) ; } // ’x ’ here is a local copy
3 int main () {
4 test ( x ) ;
5 printf ( " % d " ,x ) ; // Does the global ’x ’ change ?
6 return 0;
7 }
8
4. Write a C program to find a substring within a main string using pointers.
5. Write a function that calculates the length of a string (like ‘strlen‘) using only pointers.
6.2 Pass by Reference
By passing the address of a variable (using a pointer), the function can dereference it and change
the original variable’s value.
Example
1 // swap function using pointers ( pass by reference )
2 // It takes addresses ( pointers ) as arguments
3 void swap ( int *a , int * b ) {
4 int temp = * a ; // Get the value AT address ’a ’
5 *a = *b; // Set the value AT address ’a ’ to the value AT ’b ’
6 * b = temp ; // Set the value AT address ’b ’ to temp
7 }
8
9 int main () {
10 int x = 5 , y = 10;
11 printf ( " Before swap : x = %d , y = % d \ n " , x , y ) ;
12
13 // We pass the addresses of x and y
14 swap (& x , & y ) ;
15
16 printf ( " After swap : x = %d , y = % d \ n " , x , y ) ; // x is now 10 , y is 5
17 return 0;
18 }
10
Programming Exercises
1. Write a function ‘addTen(int *ptr)‘ that accepts an integer pointer and adds 10 to the
value it points to.
2. Write a function ‘calculate(int a, int b, int *sum, int *product)‘ that takes two integers
and returns their sum and product via pointer parameters.
3. Write a function ‘findMinMax(int arr[], int size, int *min, int *max)‘ that takes an array
and returns its minimum and maximum values via pointers.
4. Write a function to calculate the area and perimeter of a rectangle, taking length, width,
and two pointers ‘*area‘ and ‘*perimeter‘ to return the results.
5. Predict the output (Pass by Reference):
1 void test ( int * x ) { * x =* x +1; printf ( " % d " ,* x ) ; }
2 int main () {
3 int x =5;
4 test (& x ) ; // Passing the address
5 printf ( " % d " ,x ) ; // What is the final value of x ?
6 return 0;
7 }
8
7 Other Pointer Topics
• Double Pointers: ‘int **pptr;‘ (A pointer that points to another pointer).
• Void Pointers: ‘void *ptr;‘ (A generic pointer that can point to any data type, requires
casting before use).
• Array of Pointers: ‘char *nameList[10];‘ (An array of 10 pointers, where each pointer
can point to a string).
• Pointers to Functions: Allows passing functions as arguments to other functions (used
for callbacks, etc.).
Programming Exercises
1. Write a C program to store an array of 5 integers using ‘malloc‘ and then print them.
2. Write a C program to sort an array of strings using an array of pointers.
3. Write a C program that uses a function pointer to call one of two functions (add or subtract)
based on user choice.
4. Predict the output (Double Pointer):
1 int main () {
2 int x =10;
3 int * p = & x ;
4 int ** pp = & p ; // Pointer to a pointer
5
6 ** pp = 15; // Changes the value at the final address
7
8 printf ( " % d " , x ) ; // What does x print ?
9 return 0;
10 }
11
11
5. Write a function that accepts a ‘void*‘ pointing to a number (either an ‘int‘ or a ‘float‘)
and a ‘flag‘ (0 for int, 1 for float) and prints the value.
Part III
Structures and Unions
8 Structures (Struct)
A structure is a user-defined data type that allows grouping variables of different data types
together under a single name.
8.1 Declaration and Initialization
Example
1 // Declare a template for struct Student
2 // This defines a new type , but doesn ’t create any variables
3 struct Student {
4 char name [50];
5 int age ;
6 float gpa ;
7 }; // Must have semicolon at the end
8
9 int main () {
10 // Declare a variable of type struct Student
11 struct Student s1 ;
12
13 // Initialize variable at declaration
14 struct Student s2 = { " Nguyen Van A " , 20 , 3.5};
15
16 return 0;
17 }
Programming Exercises
1. Create a ‘struct‘ "Cricket" with fields: Player Name, Team Name, Average. Read and
display the records of 5 players.
2. Write a program to store and print the roll number, name, age, and score of one student
using a ‘struct‘.
3. Enter the marks of 5 students for 3 subjects using a ‘struct‘. Display the percentage for
each student.
4. Create a ‘struct‘ ‘Date‘ (day, month, year). Write a program to compare two dates.
5. Write a program for a library using a ‘struct‘ ‘Book‘ (number, author, title, borrowed_flag).
8.2 Accessing Members
Use the dot operator (.) to access the internal members of a structure variable.
12
Example
1 struct Student s1 ;
2
3 // Use strcpy for string members
4 strcpy ( s1 . name , " Tran Thi B " ) ;
5 s1 . age = 21;
6 s1 . gpa = 3.8;
7
8 printf ( " Name : % s \ n " , s1 . name ) ;
9 printf ( " Age : % d \ n " , s1 . age ) ;
Programming Exercises
1. Write a C program to add, subtract, and multiply two complex numbers using structures.
2. Predict the output:
1 int main () {
2 struct CBook { char * name ; int year ; };
3 struct CBook c1 = { " Learn to Code " , 2020};
4 // When a struct is assigned to another , all members are copied .
5 struct CBook c2 = c1 ;
6 printf ( " % s % d " , c2 . name , c1 . year ) ;
7 return 0;
8 }
9
3. Find the error:
1 int main () {
2 struct employee {
3 int empid [5];
4 int salary ;
5 employee * s ; // Error : typedef name ’ employee ’ not found
6 } emp ;
7 // Fix : should be ’ struct employee * s ; ’
8 printf ( " % d " , sizeof ( struct employee ) ) ; // Need ’ struct ’ keyword
9 return 0;
10 }
11
4. Write a C program using a ‘struct‘ to store a ‘Point‘ (x, y) and calculate its distance from
the origin.
5. Write a C program using a ‘struct‘ to store an ‘Employee‘ (Name, Salary) and give the
employee a 10% raise.
8.3 Structures and Pointers
When you have a pointer to a structure, use the arrow operator (->) to access its members.
It is a shortcut for ‘(*ptr).member‘.
Example
1 struct Student s1 = { " Nguyen Van A " , 20 , 3.5};
2 struct Student * pS ; // Declare pointer of type struct Student
3
4 pS = & s1 ; // Point pS to the address of s1
5
13
6 // Access using arrow operator ( - >)
7 printf ( " Name ( using pointer ) : % s \ n " , pS - > name ) ;
8 printf ( " Age ( using pointer ) : % d \ n " , pS - > age ) ;
9
10 // Equivalent ( but less common ) syntax
11 // printf (" Name : % s \ n " , (* pS ) . name ) ;
Programming Exercises
1. Write a function ‘printBook(struct Book *b)‘ that takes a pointer to a ‘Book‘ struct (from
the previous exercise) and prints its information.
2. Write a function ‘updatePages(struct Book *b, int newPages)‘ that takes a ‘Book‘ pointer
and updates its page count.
3. Modify the exercise storing 5 students to use an array of pointers to 5 ‘struct Student‘
variables instead of an array of structs.
4. Write a C program to create a ‘struct‘ and access its members using a pointer.
5. Write a function that takes a pointer to a ‘Point‘ struct (x, y) and moves the point 5 units
on both the x and y axes.
8.4 Arrays of Structures
We can create arrays of structures, which is useful for managing a list of objects.
Example
1 // Declare an array capable of holding 30 Student structs
2 struct Student class [30];
3
4 // Access the first student ( at index 0)
5 class [0]. age = 21;
6 strcpy ( class [0]. name , " Le Van C " ) ;
Programming Exercises
1. Write a program using an array of structures to store 5 ‘struct Point‘ (x, y) input by the
user.
2. From Exercise 1, add code to find the point in the array furthest from the origin (0,0).
3. Rewrite the exercise for entering marks for 5 students using an array of structures.
4. Rewrite the library exercise using an array of ‘Book‘ structures.
5. Write a C program to sort an array of structures (e.g., ‘struct Student‘) based on a member
(e.g., ‘gpa‘).
8.5 Nested Structures
A structure can contain another structure as one of its members.
14
Example
1 struct Date {
2 int day ;
3 int month ;
4 int year ;
5 };
6
7 struct Student {
8 char name [50];
9 struct Date birthday ; // Nested structure
10 };
11
12 int main () {
13 struct Student s1 ;
14
15 // Access nested members using the dot operator twice
16 s1 . birthday . day = 15;
17 s1 . birthday . month = 10;
18 s1 . birthday . year = 2003;
19
20 printf ( " Student ’s birth month : % d \ n " , s1 . birthday . month ) ;
21 return 0;
22 }
Programming Exercises
1. Write a C program to compare two dates (using a nested ‘struct Date‘ if desired).
2. Create a ‘struct Calendar‘ (day, month, year). Add 50 days to the current date and print
the new date.
3. Create an ‘struct Employee‘ that contains a nested ‘struct Address‘ (street, city, zip code).
4. Write a program to input an array of 5 ‘Employee‘s (from the previous exercise) and print
their information.
5. Write a C program using nested structs to store ‘Employee‘ info including ‘ID‘ and ‘Date-
OfJoining‘ (day, month, year).
9 Unions
A union is similar to a struct, but all its members share the same memory location. Only
one member can hold a value at any given time.
9.1 Declaration and Use
Example
1 union Data {
2 int i ;
3 float f ;
4 char str [20];
5 }; // Size of this union will be size of the largest member ( char str [20])
15
Programming Exercises
1. Declare a ‘union‘ named ‘Data‘ that can hold 1 ‘int‘, 1 ‘float‘, or 1 ‘char‘.
2. Write a C program to demonstrate that ‘union‘ members share the same memory address
(use ‘printf("
3. Predict the output:
1 int main () {
2 union demo { int x ; int y ; };
3 union demo a;
4 a . x = 100;
5 a . y = 200; // This overwrites the value of a . x
6 printf ( " % d % d " , a .x , a . y ) ;
7 return 0;
8 }
9
4. Predict the output:
1 int main () {
2 union Data { int i ; float f ; };
3 union Data d ;
4 d . f = 10.5;
5 // Accessing d . i will read the ’ int ’ representation
6 // of the bits stored by the ’ float ’ 10.5.
7 printf ( " % d " , d . i ) ; // What is printed ? ( Likely garbage / unexpected int )
8 return 0;
9 }
10
5. Create a ‘union‘ that can store an ‘int‘, ‘float‘, or ‘double‘. Print the size of this ‘union‘.
9.2 Difference between Struct and Union
• Memory:
– Struct: Allocates enough memory to hold all members. The size is the sum of
member sizes (plus padding).
– Union: Allocates memory only large enough for the largest member.
• Usage:
– Struct: Stores multiple different values at the same time.
– Union: Stores only one value from its list of members at a time. Useful for saving
memory when only one of many types is needed.
Example
1 union Data {
2 int i ;
3 float f ;
4 };
5
6 union Data data ;
7 data . i = 10;
8 printf ( " data . i : % d \ n " , data . i ) ; // data . i is 10
9
10 data . f = 220.5;
16
11 printf ( " data . f : % f \ n " , data . f ) ; // data . f is 220.5
12
13 // !! data . i now contains garbage , as data . f ( the float )
14 // !! has overwritten the memory location .
15 printf ( " data . i ( after assigning f ) : % d \ n " , data . i ) ;
Programming Exercises
1. Write a C program to declare an ‘enum‘ for colors (RED, GREEN, BLUE) and print their
integer values.
2. Write a C program that uses ‘typedef‘ to create the alias ‘Integer‘ for the ‘int‘ type and
use it to declare a variable.
3. Write a ‘struct‘ that uses bitfields to store ‘flags‘ for 8 settings (1 bit each). Print the size
of this ‘struct‘.
4. Write a C program to declare a ‘struct Date‘ with bitfields: ‘day‘ (5 bits), ‘month‘ (4 bits),
‘year‘ (12 bits). Print the size of this ‘struct‘.
5. Write a self-referential ‘struct Node‘ for a linked list, containing an integer ‘data‘ and a
pointer ‘*next‘.
17
Final Review Exercises
1. Write a C program that declares an array of 10 integers. Write a function that accepts this
array and its size, and returns the largest element in the array.
2. Write a C program that declares 2 integer variables. Write a ‘swap()‘ function that uses
pointers to swap the values of these two variables.
3. Define a ‘struct‘ named ‘Book‘ that includes the members: ‘title‘ (string), ‘author‘ (string),
and ‘pages‘ (integer). Create an array of 3 books, input their information, and print it to
the screen.
18