You are on page 1of 14

Advanced

C Programming
[T]EE2028 - Lecture 4
Dr Henry Tan, ECE, NUS
E-mail: eletanh@nus.edu.sg
Lecture 4: Advanced C Programming
Objectives:
 To review essential advanced C programming concepts
used in this module

Outline:
 1. Arrays
 2. Structures
 3. Pointers
 4. Pointers to Structures

[T]EE2028 Lecture 4: Advanced C Programming 2


© Dr Henry Tan, ECE NUS
1. Arrays
 An array is a storage of multiple data items
that have a common data type, e.g. char, int, float, etc.
 It can be visualized as a set of contiguous cells, with
each cell taking one item/element The 3 aspects of every memory cell:
Address, Value and User-defined
name (label, variable name, etc).
Address Memory Remarks
Did you know that by itself, the array variable name
E.g. 0x……10 1 x[0] (base addr)
refers to the address of its first element? I.e. x = &x[0]
14 2 x[1]
18 3 x[2] Offset
1C 4 :
 One-Dimensional Array 20 5 :
: : :
 e.g. int x[100]; 19C 100 x[99]
  integer array capable of storing 100 integer values
 The first element is referred to as x[0] and
the last element is x[99]
[T]EE2028 Lecture 4: Advanced C Programming 3
© Dr Henry Tan, ECE NUS
1. Arrays – 2D
 Two-Dimensional Array
 Same definition as one-dimensional arrays, common data type
 For each high-level subscript, there is a one-dimensional
array of values stored contiguously, i.e. array of array
 e.g. float mydata[8][25];
  200 float-type elements, starting from [0][0] to [7][24]
 Think of this as a matrix with row and column subscripts
 e.g. int y[3][4] = { {1,2,3,4},
{5,6,7,8},
{9,10,11,12}
}; Address Memory Remarks
E.g. 0x……10 1 y[0][0]
14 2 y[0][1]  Row-
18 3 y[0][2] major
1C 4 y[0][3] order
20 5 y[1][0]
: : :
[T]EE2028 Lecture 4: Advanced C Programming 3C 12 y[2][3] 4
© Dr Henry Tan, ECE NUS
1. Array – Passing Multi-Dimensional Array
to a Function by Value (Any problem?)
#include <stdio.h>

void displayChars(char chr[2][2]); // function declaration

int main()
{
char arr[2][2], i, j;
printf("Enter 4 characters:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
scanf("%c", &arr[i][j]);
// passing multi-dimensional array to displayChars
displayChars(arr);

}
return 0;
Remarks: Output:
arr[0][0]=a Enter 4 characters:
void displayChars(char chr[2][2]) // function definition arr [0][1]=b abcd
{ arr [1][0]=c Displaying:
// void displayChars (char chr[][2]) is also valid arr [1][1]=d a
int i, j; b
printf("Displaying:\n"); c
for (i = 0; i < 2; ++i) d
for (j = 0; j < 2; ++j)
printf("%c\n", chr[i][j]);
}

[T]EE2028 Lecture 4: Advanced C Programming 5


© Dr Henry Tan, ECE NUS
2. Structures
 Object containing a set of members
 Members can be of different data types
 The general form:
struct students /* students is the name of this structure */
{
< all members declared here >
/* e.g. char name[30]; int phone; float score; */

}; /* structure definition must always end with a semi-colon */

/* No memory is allocated until its variable is created


* To create variable(s) of data type “struct students”: */

struct students st1;


struct students st2, st3, st4;

[T]EE2028 Lecture 4: Advanced C Programming 6


© Dr Henry Tan, ECE NUS
2. Structures – typedef
 May be simplified with the typedef keyword
 Results in a cleaner & more readable code
typedef struct ece /* the name ece is optional */
{
char name[30];
int phone;
float score;
} students; /* students is a “struct ece” variable */

students st1; /* instead of struct students */


students st2, st3, st4;

strcpy(st1.name,“Adam");
st1.phone = 87654321;
st1.score = 90.5;

structure member operator (.)


[T]EE2028 Lecture 4: Advanced C Programming 7
© Dr Henry Tan, ECE NUS
3. Pointers

 The advantages of using pointers include: they


 Enable efficient handling of arrays and structures
 Enable efficient passing of data to functions
 Improve code readability
 Provide a way to perform dynamic memory allocation and
deallocation
 Provide direct access to memory (beware: with pointer, a program
can technically access any memory location in the computer’s memory)
 Enable creation of complex data structures such as linked lists,
queues, stacks, trees and graphs.

[T]EE2028 Lecture 4: Advanced C Programming 8


© Dr Henry Tan, ECE NUS
3. Pointers – Address Operator
 A pointer is a variable that represents the location of a data item
 Let us consider a variable, v, that represents a data item
 & is a unary operator called the address operator that evaluates
the memory address of its operand
 Thus, the address where the value of variable v is stored is
determined by the expression &v (which is also a number!)
 If we let pv = &v,
 pv is then called a pointer to the variable v since it “points” to
the memory location where (the value of) v is stored
 i.e. the address of the variable v is stored in the variable pv.

pv Address of v v Value of v
e.g. 0x20000000 e.g. 0x10002000 0x10002000 e.g. 5
[T]EE2028 Lecture 4: Advanced C Programming
(&v) 9
© Dr Henry Tan, ECE NUS
3. Pointers – Indirection Operator
 But if we want to access the value of a variable
instead of its memory address, we use:
 *, the unary operator called the indirection operator (aka
dereference operator) that evaluates the value of its operand
 Note: * operates only on a pointer variable (e.g. pv)
 Thus, the value of the variable v can be determined by the
expression *pv, which returns the same contents as v
 If v is a structure, pointer pv provides an alternative way to
access its member
 Pointer operators comparison and memory view:
e.g. int* p; int * p; int *p; are
equivalent pointer declarations
Address Memory Remarks
E.g. 0x….1010 20 x  p
int x, y, *p; 1014 28 y
: : :
x = 20; y = 28; 301C 0x….1010 p
p = &x; 3020 20 *p (=z)
z = *p; : : :
[T]EE2028 Lecture 4: Advanced C Programming 4018 0x….1014 &y 10
© Dr Henry Tan, ECE NUS
4. Pointers to Structures:

 The advantages of using pointers to structures (PtS) include: they


 Allow efficient passing of structures to functions:
pass the address of structure instead of the entire structure to functions
(i.e. the function argument is a PtS rather than the structure itself)
the time needed to perform the pass is independent of the struct size
the called function modifies directly the struct variable defined in the
calling function, thus avoids making a copy of the struct variable
 Allow efficient management of the dynamically-memory-
allocated structures
 Enable access of a variable that is defined outside the function
 Enable the return of more than one value from the function

[T]EE2028 Lecture 4: Advanced C Programming 11


© Dr Henry Tan, ECE NUS
4. Pointers to Structures:
For Passing Structures to Functions
#include <stdio.h>
#include <string.h> Data members can be accessed via a pointer to
/* Pointer-to-Structure (PtS) example */ the structure using the pointer operator (->) ,
instead of the structure member operator ( . )
typedef struct student
{
that is used when the members are accessed
int id; directly via the structure’s name. In other words,
char name[30];
PtS-> member is a shorthand for (*PtS).member
float score;
} student_record;

void print_rec(student_record *X) // *X is a PtS of student_record type


{
printf("Record of STUDENT: \n");
printf(" Id is: %d \n", X->id);
printf(" Name is: %s \n", X->name);
printf(" Score is: %f \n", X->score);
printf("\n");
}

void update_score(student_record *X, float newscore)


{
X->score = newscore;
}

[T]EE2028 Lecture 4: Advanced C Programming 12


© Dr Henry Tan, ECE NUS
4. Pointers to Structures:
For Passing Structures to Functions
int main()
{
student_record student1 = {1, “Adam", 90.5};
student_record *sptr; // declare sptr as a PtS

sptr = &student1; // "&" operator gets the address of the data object

print_rec(sptr); // print structure members via the PtS


update_score(sptr, 98.7); // updates “score" member to 98.7 via the PtS
print_rec(sptr);

return 0;
}

Output:
Record of STUDENT:
Id is: 1
Name is: Adam
Score is: 90.500000

Record of STUDENT:
Id is: 1
Name is: Adam
Score is: 98.700000
[T]EE2028 Lecture 4: Advanced C Programming 13
© Dr Henry Tan, ECE NUS
THE END
Questions?

[T]EE2028 Lecture 4: Advanced C Programming


© Dr Henry Tan, ECE NUS

You might also like