View
216
Download
0
Tags:
Embed Size (px)
Citation preview
CIS 101: Computer Programming and Problem Solving
Lecture 9Usman Roshan
Department of Computer Science
NJIT
C++ functions
Function definition:
<return value> <function_name> (<arg1_type> <arg1>, <arg2_type> <arg2>,…,<argn_type> <argn>);
For example, int myadd(int x, int y)lint max(int x, int y);
C++ functions
Compiler goes from top to bottom. So, either
(1) Declare function before main() and then define it anywhere in the file
(2) Or define it before main()
Pointers and reference
int x=2; int *y;
y = &x;
2 2
Memory
Memory is organized into cells. Let’s say x is in cell number 100
100
Returns memorylocation of thevariable
x
yx
y is a pointer to an integer. We set it to point to x which means it will now containthe memory location of x.
Dynamic memory allocation---creating and deleting arrays of arbitrary size
int *x;
x = new int[1];
We first create an array pointer and then
create space in memory for one integer it
can point to.
Output of pointer programx is a pointer to a location in memory which is why it shows up in HEX
The memory location x points to contains 2.
Dynamic arrays
int *x;
x = new int(3);
x[0] = 2;
x[2] = 4;
x[3] = 6;
Memory
x
50 2
x[0]
4 6
x[1] x[2]
Dynamic arrays
• Memory defined using new must be cleared up using delete. Otherwise your program may use up ALL the memory.
int *x = new int[10];
.
.
delete x;
Passing variables by value
A new variable is createdthat contains a copy of x
This means the value in the original variableis unchanged.
Passing variables by reference
& means we are receiving areference to the original variableand it can be modified.
Now the value in the original variablex can be modified.
Two dimensional arrays
2D arrays are defined asint A[10][10];This allocates space for a 2-D array of dimension 10 times 10, with un-initializedvalues.You can also doint *a[10];This creates an array of 10 integer pointers forwhich space has to be allocated using new.