Professional Documents
Culture Documents
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
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]);
}
strcpy(st1.name,“Adam");
st1.phone = 87654321;
st1.score = 90.5;
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:
sptr = &student1; // "&" operator gets the address of the data object
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?