辅导ELEC5681M、Programming讲解、辅导C++、C/C++程序设计调试

- 首页 >> 其他
MC (11/19) Page 1 of 9
ELEC5681M Programming
Week 9 – Advanced structures in C
School of Electronic & Electrical
Engineering
FACULTY OF ENGINEERING
MC (11/19) Page 2 of 9
Table of Contents
Table of Contents 2
Introduction 3
Functions 4
Pointers 6
Structures 8
MC (11/19) Page 3 of 9
Introduction
Today you will be looking at advanced structures in C: functions, pointers and structures.
Always remember that when compilation fails, the compiler’s error message(s) will help you to
pinpoint the problem(s).
MC (11/19) Page 4 of 9
Functions
So far we have been writing all the code in the main() function. In this section, you will look at
some code which contains functions and add some of your own.
C functions are simple, but because of how C works, the power of functions is a bit limited.
 Functions receive either a fixed or variable amount of arguments.
 Functions can only return one value, or return no value.
In C, arguments are copied by value to functions, which means that we cannot change the
arguments to affect their value outside of the function. To do that, we must use pointers, which are
discussed later on.
Functions are defined using the following syntax:
int foo(int bar) {
/* do something */
return bar * 2;
}
int main() {
foo(1);
}
The function foo we defined receives one argument, which is bar. The function receives an
integer, multiplies it by two, and returns the result. The body of the function is enclosed within curly
brackets { }.
To execute the function foo with 1 as the argument bar, we use the following syntax:
foo(1);
In C, functions must be first defined before they are used in the code. They can be either declared
first, and then implemented later on, using a header file or in the beginning of the C file, or they can
be implemented in the order they are used (less preferable).
The correct way to use functions is as follows:
/* function declaration */
int foo(int bar);
int main() {
/* calling foo from main */
printf("The value of foo is %d", foo(1));
}
int foo(int bar) {
return bar + 1;
}
MC (11/19) Page 5 of 9
We can also create functions that do not return a value by using the keyword void:
void moo() {
/* do something and don't return a value */
}
int main() {
moo();
}
Using functions is an important aspect of programming: breaking the code down into smaller, more
manageable chunks of code, makes it easier to test, debug and maintain a code.
Task 1:
• Open up the ‘Shapes2.c’ example and read through the comments to see what is going on.
• Compile and run.
• Add functions to calculate the following geometry related things (Test after each function. Use
flowcharts and pseudocode to help to design your software):
• area of a triangle
• volume of a cube
• volume of a sphere
MC (11/19) Page 6 of 9
Pointers
Pointers are also variables and play a very important role in C. They are used for several reasons,
such as:
 Defining strings
 Dynamic memory allocation
 Sending function arguments by reference
 Building complicated data structures
 Pointing to functions
 Building special data structures (i.e. Tree, Tries, etc...)
 And many more…
What is a pointer?
A pointer is essentially a simple integer variable which holds a memory address that points to a
value, instead of holding the actual value itself.
The computer's memory is a sequential store of data, and a pointer points to a specific part of the
memory. Our program can use pointers in such a way that the pointers point to a large amount of
memory - depending on how much we decide to read from that point on.
Strings as pointers
We've already discussed strings, but now we can dive in a bit deeper and understand what strings
in C really are (which are called C-Strings to differentiate them from other strings when mixed with
C++)
The following line:
char * name = "John";
does three things:
1. It allocates a local (stack) variable called name, which is a pointer to a single character.
2. It causes the string "John" to appear somewhere in the program memory (after it is
compiled and executed, of course).
3. It initializes the name argument to point to where the J character resides (which is followed
by the rest of the string in the memory).
If we try to access the name variable as an array, it will work, and will return the ordinal value of the
character J, since the name variable actually points exactly to the beginning of the string.
Since we know that the memory is sequential, we can assume that if we move ahead in the
memory to the next character, we'll receive the next letter in the string, until we reach the end of
the string, marked with a null terminator (the character whose ordinal value is 0, noted as \0).
Dereferencing
Dereferencing is the act of referring to where the pointer points at, instead of the memory address.
We are already using dereferencing in arrays - but we just didn't know it yet. The brackets operator
- [0] for example, accesses the first item of the array. And since arrays are actually pointers,
accessing the first item in the array is the same as dereferencing a pointer. Dereferencing a pointer
is done using the asterisk operator *.
MC (11/19) Page 7 of 9
If we want to create an array that will point to a different variable in our stack, we can write the
following code:
/* define a local variable a */
int a = 1;
/* define a pointer variable, and point it to ‘a’ using the & operator
*/
int * pointer_to_a = &a;
printf("The value a is %d\n", a);
printf("The value of a is also %d\n", *pointer_to_a);
Notice that we used the & operator to point at the variable a, which we have just created.
We then referred to it using the dereferencing operator. We can also change the contents of the
dereferenced variable:
int a = 1;
int * pointer_to_a = &a;
/* let's change the variable a */
a += 1;
/* we just changed the variable a again! */
*pointer_to_a += 1;
/* will print out 3 */
printf("The value of a is now %d\n", a);
Task 2:
 Open ‘pointer1.c’
 Create a pointer to the local variable n called pointer_to_n, and use it to increase the
value of n by one.
 What is the difference between pointer_to_n and *pointer_to_n?
 Compile and test
MC (11/19) Page 8 of 9
Structures
C structures are special, large variables which contain several named variables inside. Structures
are the basic foundation for objects and classes in C++. Structures are used for:
 Serialization of data
 Passing multiple arguments in and out of functions through a single argument
 Data structures such as linked lists, binary trees, and more
The most basic example of structures are points, which are a single entity that contains two
variables - x and y. Let's define a point in a two-dimensional point:
struct point {
int x;
int y;
};
Now, let's define a new point, and use it. Assume the function draw receives a point and draws it
on a screen. Without structures, using it would require two arguments - each for every coordinate:
/* draws a point at 10, 5 */
int x = 10;
int y = 5;
draw(x, y);
Using structures, we can pass a point argument:
/* draws a point at 10, 5 */
struct point p;
p.x = 10;
p.y = 5;
draw(p);
To access the point's variables, we use the dot . operator.
Typedef
Typedef allows us to define types with a different name - which can come in handy when dealing
with structures and pointers. In this case, we'd want to get rid of the long definition of a point
structure. We can use the following syntax to remove the struct keyword each time we want to
define a new point:
typedef struct {
int x;
int y;
} point;
This will allow us to define a new point like this:
point p;
MC (11/19) Page 9 of 9
Structures can also hold pointers - which allows them to hold strings, or pointers to other structures
as well - which is their real power. For example, we can define a vehicle structure in the following
manner:
typedef struct {
char * brand;
int model;
} vehicle;
Since brand is a char pointer, the vehicle type can contain a string (which, in this case, indicates
the brand of the vehicle).
vehicle mycar;
mycar.brand = "Ford";
mycar.model = 2007;
Task 3:
 Open ‘structures.c’
 Define a new data structure, named "person", which contains a string (pointer to char)
called name, an integer called age and another string called status.
 Compile and test
 Now (without using typedef) define a 3D point with coordinates (0.001,0.72,13.5) and
print these coordinate on the screen.
.