Here are the values of some pointer expressions using a and p:
p: Points to the first element of a, which is 10
*p: 10 (the value at the address p points to)
p+1: Points to the second element of a, which is 20
*(p+1): 20
&(p+1): Points to the address of p+1
p-1: Not valid, as p is pointing to the first element already
Entry point
Required uniqueentry point
The most common is: main
void main()
{
// your code here
}
Form1.cpp
int main(int n, char ** args)
{
// your code here
}
Form2.cpp
1>LINK : fatal error LNK1561: entry point
must be defined
Error when no entry point is defined
15
C/C++ standard library
C/C++support a set of internal
basic library, such as
• Basic IO
• Math
• Memory handle
• …
For using, include the header
file
#include <…>
#include "…"
#include "stdio.h"
void main()
{
printf("hello");
}
17
18.
C header C++header
<assert.h> <cassert> Content assert macro, for debugging
<Ctype.h> <cctype> For character classification/convert functions
<Errno.h> <cerrno> For testing error number
<float.h> <cfloat> Floating point macros
<limits.h> <climits> Define range of value of common type
<math.h> <cmath> Mathematical functions
<setjmp.h> <csetjmp> Provide “non-local jumps” for flow control
<signal.h> <csignal> Controlling various exceptional conditions
<stdlib.h> <cstdlib> Standard lib
<stddef.h> <cstddef>
<stdarg.h> <cstdarg>
<stdio.h> <cstdio> Standard IO
<string.h> <cstring> Manipulating several kinds of string
<time.h> <ctime> Converting between time & date formats
<wchar.h> <cwchar>
<wctype> <cwctype> 18
19.
C/C++ user-defined lib
NotC/C++ standard lib
Come from:
• Third-party
• User own
In common, include 2 parts
• .h files & .lib files: for developer
• .dll file (dynamic library): for end-user
error LNK2019: unresolved external symbol
Error caused when forget to add .lib file
19
20.
C/C++ user-defined lib(cont.)
For using
• Include .h files
• Inform .lib files to compiler
• Copy all .dll file to (if any) :
o same folder with execute file, or
o to system32 (windows) – not recommend
20
21.
Declare path to.lib
Import user-defined library
Visual studio
21
Global & local
intmGlobalVar;
void Foo()
{
int localVar;
printf("Foo : %d %dn",
localVar, mGlobalVar);
}
int main()
{
int localVar = 1;
printf("Main: %d %dn",
localVar, mGlobalVar);
mGlobalVar = 1;
Foo();
return 1;
}
Global variable
• Available in all of program
• Set default value to zero
Local variable
• NO default value
• Available inside block
Main: 1 0
Foo : 2280752 1
Command prompt
28
29.
Auto variable
As default,a variable is a auto variable
int myVar auto int myVar
Go out of scope once the program exits from the
current block
29
30.
Static variable
Allocated whenthe program
starts and is deallocated when
the program ends.
Default value is zero (0)
#include <cstdio>
static int s_iGlobalStatic;
void Foo()
{
static int s_iLocalStatic;
printf("Foo: called %dn",
s_iLocalStatic++);
}
int main()
{
int localVar = 1;
printf("Main: %dn",
s_iGlobalStatic);
Foo();
Foo();
Foo();
return 1;
}
Main: 0
Foo: called 0
Foo: called 1
Foo: called 2
Command prompt
30
31.
Register variable
Stored ina machine register if
possible
Usually used in “for iterator”
for improve performance
int main()
{
int sum = 0;
for (register int i = 0;
i < 100;
i++)
{
sum += i;
}
printf("Sum = %dn", sum);
return 1;
}
31
32.
Extern variable
Specify thatthe variable is
declared in a different file.
Compiler will not allocate
memory for the variable
Avoid duplicate declaration
Share (global) variable for
multiple .cpp files
#include <cstdio>
extern int m_iExternVar;
int main()
{
printf("Value = %dn",
m_iExternVar);
return 1;
}
main.cpp
int m_iExternVar = 100;
Extern.cpp
Value = 100
Command prompt
32
33.
Constant
Variable's value isconstant
To prevent the programmer from modifying
int const k_Hello = 0;
int main()
{
k_Hello = 10;
}
error C3892: 'k_Hello' : you cannot assign to
a variable that is const
Error
33
Primitive data type
(32bitsprocessor)
Type Size Range
void n/a
char 1 byte unsigned char: -128 … 127
signed char: 0…255
short 2 bytes unsigned short: 0 … (216 -1)
signed short: -215 … (215 – 1)
int 4 bytes
-231 … (231 – 1)
unsigned int: 0 … (232 -1)
signed int: -231 … (231 – 1)
long 4 bytes
-231 … (231 – 1)
unsigned long: 0 … (232 -1)
signed long: -231 … (231 – 1)
long long 8 bytes
-263 … (263 – 1)
unsigned long long: 0 … (264 -1)
signed long long: -263 … (263 – 1)
bool 1 byte True /false (non-zero / zero)
float 4 bytes
double 8 bytes 35
36.
New type definition
Usetypedef
36
typedef int Mytype;
typedef int MyArr[5];
Mytype var1;
MyArr arr;
37.
sizeof operator
0 Returnsize (in byte) of a type, data structure, variable
int sizeInt = sizeof(int);
int sizeLong = sizeof(long);
char a;
int sizeA = sizeof(a);
Return 4
Return 4
Return 1
37
Array
Used to storeconsecutive values of the same data types
int b[4] = {1, 2, 3, 4};
n-dimensions array
int b[<s1>][<s2>]…[<sn>] si MUST BE constant
Index of array is counted from 0 to (si-1)
C/C++ do not handle out-of-range exception
int b[4] = {1, 2, 3, 4};
for (int i = 0; i < 4; i++)
{
printf("%dn", b[i]);
}
printf("%dn", b[10]);
b[10] = ?
39
40.
Array Assignment
40
int a[4]= {1, 2, 3, 4};
int a[] = {1, 2, 3, 4};
int a[4];
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 4;
int a[4] = {1};
a[0], a[1],
a[2], a[3] = ?
int a[4];
memset(a, 0, 4*sizeof(int));
Pointer
Computer's memoryis made up of bytes.
Each byte has a number, an address, associated with it.
0x01 0x02 0x03 0x01 0x05 0x06 0x07 0x08
When storing a variable, such as int i = 1
0x00 0x00 0x00 0x01
0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08
i
o i = 1
o &i = 0x01 & operator: get address of a variable
42
43.
Pointer (cont.)
For storingaddress of a variable, use a special type:
pointer
int *pi; char *pc; float *pf;
Pointer of a
integer variable
Pointer of a
char variable
Pointer of a
float variable
int *pi = &i;
43
int* pi;
pi = &i;
0x10 0x00 0x00 0x00
0xF1 0xF2 0xF3 0xF4 0xF5 0xF6 0xF7 0xF8
i
&i
44.
Pointer (cont.)
Pointer isalso a variable it’s stored in memory
int i = 10;
int *p
i = 100x2f00002c
0x2f00aabb p
p =
&p =
*p =
*p : get value at address pointed by p
44
0x2f00002c
0x2f00aabb
10
= &i;
= 0x2f00002c
45.
Pointer (cont.)
Type ofpointer notify that how to get the value
pointed by pointer
int i = 0x3f20cc01;
char *p1 = (char *)&i;
short *p2 = (short *)&i;
int *p3 = &i;
p1 is pointed to char-block. *p1 =
p2 is pointed to short-block. *p2 =
p3 is pointed to int-block. *p3 =
P1 P2
0x01 0xcc 0x20 0x3f
0xF1 0xF2 0xF3 0xF4 0xF5 0xF6 0xF7 0xF8
i Little Endian
P3
45
0x01
0xCC01
0x3f20cc01
46.
Pointer (cont.)
sizeof operator
Sizeof pointer is not belong to type of pointer
Size of pointer depend on processor (16 bits, 32 bits, 64
bits)
• For windows 32 bits: size of pointer is 4 bytes
int main()
{
char c = 0;
char *p = &c;
printf("size = %d", sizeof(p));
}
46
47.
Pointer
pointer operator
Note:each step is a distance k bytes
belongs to type of pointer:
• byte: 1 byte
• Short: 2 byte
• ….
Operat
or
desc Example
+ move forward n steps p += 10;
- move backward n step p -= 1;
++ move forward 1 step p++;
-- move backward 1 step p--;
0x01 0xcc 0x20 0x3f 0x00 0x10 0xaa
0x01 0x02 0x03 0x04 0x05 0x06 0x07
p1 p1+1 p1+5
0x01 0xcc 0x20 0x3f 0x00 0x10 0xaa
0x01 0x02 0x03 0x04 0x05 0x06 0x07
p2 p2+1 p2+3
char *p1; short *p2;
(p1+1) (p2 + 1)
*(p1+1) *(p2+1)
&(p1+1) &(p2+1)
47
Pointer to pointer
Recallthat, a pointer variable is a variable.
To store address of a pointer variable, we use pointer-
to-pointer variable.
49
int iVar = 10;
int *p1 = &iVar;
int **p2 = &p1;
iVar = 10
p1 = 0x100
p2 = 0x200
0x200
0x100
0x300
*p1 == ?
*p2 == ?
*(*p2) == ?
50.
p
nx4 bytes
Pointer
Dynamic allocation
Static allocation:
int a = 10;
int array[1000];
• Variable will be allocated in stack limited size
• Number of elements of array is const
• Can not clean up when they become useless
Dynamic allocation
• User pointer
• Allocation a block of memory in heap high capacity
• Clean up easily
Alloc n-int elements in heap
int *p = new int[n];
p
Free memory block pointed by p
50
delete p;
How about
“p” after
deleting?
51.
Pointer
Dynamic allocation (cont.)
Theretwo way for dynamic allocation
51
• Using stdlib.h
• Using malloc/free
Old C style
• Using new/delete
• Using new[] / delete[]
C++ style
int main()
{
char *i = (char*) malloc (100);
// some code here
free(i);
}
int main()
{
char *i = new char[100];
// some code here
delete []i;
}
52.
Pointer
Dynamic allocation (cont.)
Usedelete for new,
Use delete[] for new[]
52
struct A
{
public:
static int count;
int val;
A()
{
printf("Created %dn",
val = count++);}
~A()
{
printf("Deleted %dn",
val);}
};
int A::count = 0;
int main()
{
A *cA = new A[10];
delete cA;
return 1;
}
Delete cA[0] only
int main()
{
A *cA = new A[10];
delete []cA;
return 1;
}
Delete all cA
53.
Pointer-to-pointer dynamic
allocation
In common,used for allocation an 2D-array
53
int **p;
p = new int*[2];
*(p+0) = new int;
*(p+1) = new int;
p0x900
0x500
= 0x500
0x200
0x200
0x300
0x300
int **p = new int*[3];
p[0] = new int[4];
p[1] = new int[4];
p[2] = new int[4];
*(*(p + i) +j ) p[i][j]
54.
Pointer vs. Array
Incommon, pointer could be used like array
int main()
{
int *p
p[0] = 1;
*(p + 1) = 12;
p[2] = 5
}
P
0x2f330000
0x2f330004
0x2f330008
0x2f0A0000
stack
heap
*p = *(p+0) = p[0]
*(p + n) = p[n]
54
new int [3];
= 0x2f330000
1
12
5
=
55.
Pointer vs. Array
Arrayis a pointer
pointed to itself
A pointer can point to
an array addr.
int main()
{
char a[3] = {1, 2, 3, 4};
printf ("0x%x 0x%x %dn", a, &a, *a);
int *p = new int[3];
p[0] = 1; p[1] = 2; p[2] = 3;
printf ("0x%x 0x%x %dn", p, &p, *p);
int *p2 = (int*)a;
printf("value of p2 = 0x%xn", *p2);
}
0x14fd64 0x14fd64 1
0x591398 0x14fd60 1
Value of p2 = 0x04030201
Command prompt
55
Due to stacklimited, can not create a too big array
Pointer vs. Array
int main()
{
char arr[1034996];
}
int main()
{
char *p = new char[1034996];
}
FAIL OK
0 Can not delete an array
int main()
{
char arr[100];
delete arr;
}
int main()
{
char *p = new char[1034996];
delete p;
}
FAIL OK
Memory block of array is freed automatically when out-of-
scope
Dynamic memory MUST be clean manually by call “delete”
57
58.
Pointer vs. Array
2Darray
int arr[2][3]
pointer-to-pointer
int **p = new int*[2];
p[0] = new int[3];
p[1] = new int[3];
[0][0] [0][1] [0][2]
[1][0] [1][1] [1][2]
p[1]
p[0]p p[0][0] p[0][1] p[0][2]
p[1][0] p[1][1] p[1][2]
0 2D array & 2D pointer could use in the same way
arr[2][2] = 5 p[2][2] = 10
58
[0][0] [0][1] [0][2] [1][0] [1][1] [1][2]
Block 0 Block 1
*(*(p + i) +j ) p[i][j]
String
No standard stringin C/C++
Use char*, or char[] instead
String in C/C++ is array of byte, end with ‘0’
char *st = "String";
S t r i n g 0st
60
Memory utility functions
MUST#include <string.h>
void * memcpy ( void * destination, const void * source, size_t num )
Copies the values of num bytes from the location pointed
by source directly to the memory block pointed by destination
int memcmp ( const void * ptr1, const void * ptr2, size_t num )
Compare the C string pointed by source into the array pointed
by destination, including the terminating null character
63
64.
Memory utility functions
size_tstrlen ( const char * str )
• Returns the length of str
• The length of a C string is determined by the terminating null-character
• This should not be confused with the size of the array that holds the
string
char * strcpy ( char * destination, const char * source )
• Copies the C string pointed by source into the array pointed
by destination, including the terminating null character
int strcmp ( const char * str1, const char * str2 )
• Compares the C string str1 to the C string str2.
http://www.cplusplus.com/reference/clibrary/cstring/ 64
65.
Constant pointer vs.
pointerto constant
Constant pointer:
• Address of memory stored is constant
• Value at address which “pointed to” could be changed
65
Pointer to constant:
• Value at address which “pointed to” is constant
• Address of memory stored could be changed
char char_A = 'A';
const char * myPtr = &char_A;
*myPtr = 'J'; // error - can't change value of *myPtr
char char_A = 'A';
char char_B = 'B';
char * const myPtr = &char_A;
myPtr = &char_B; // error - can't change address of myPtr
Data Structure alignment
Isthe way data is arranged and accessed in computer
memory.
Consist two issue:
• Data alignment:
o Put data at memory offset equal to multiple word size
• Structure padding:
o Insert some meaningless bytes between the of last data
structure and start of next
72
GCC alignment
75
struct test_t
{
inta;
char b;
int c;
}__attribute__((aligned(8)));
struct test_t
{
int a;
char b;
int c;
}__attribute__((__packed__));
http://www.delorie.com/gnu/docs/gcc/gcc_62.html
8 byte alignment
smallest possible alignment
76.
Struct - function
C++only, not available
in C
Beside variable, struct
also has had function
Struct alignment is not
effected to struct-
function
Function is not counted
when calculate struct
size
typedef struct T_MyStruct
{
int val1;
char val2;
char val3[12];
void SayHello();
}MyStruct;
void MyStruct::SayHello()
{
printf("Hello world");
}
int main()
{
MyStruct myStruct;
myStruct.SayHello();
}
76
77.
Struct
constructor / destructor
C++only, not available in C
Two special function of struct
• Constructor: automatically call
when a instant of struct is created
• Destructor: automatically call
when a instant of struct is destroy
typedef struct T_MyStruct
{
int val1;
T_MyStruct();
~T_MyStruct();
}MyStruct;
T_MyStruct::T_MyStruct()
{
printf("Createdn");
}
T_MyStruct::~T_MyStruct()
{
printf("Destroyn");
}
int main()
{
MyStruct myStruct;
}
constructor
destructor
Created
Destroy
Command prompt
77
78.
Struct and staticmember
Static function & static
variable
Static variable is not
counted is struct
alignment and struct
size
typedef struct T_MyStruct
{
int val1;
static char val2;
static void SayHello() {}
}MyStruct;
int main()
{
MyStruct myStruct;
printf("%d", sizeof(myStruct));
MyStruct::SayHello();
}
78
79.
Struct and Accessprivilege
C++ only, not available in C
Three access privilege methods
• public: visible for all
• private: visible inside struct only
• protected: visible inside struct and
retrieved struct (OOP)
• Default is public
o For example: valx is public
79
struct MyStruct
{
int valx;
public:
int val1;
private:
int val2;
protected:
int val3;
};
int main()
{
MyStruct mine;
mine.val1 = 0;
mine.valx = 0;
mine.val2 = 0;
mine.val3 = 0;
}
Fatal Error, val2 is private
Fatal Error, val3 is protected
Default parameters
#include <cstdio>
voidfoo(int a,
int b = 1 ,
int c = 2 );
void foo(int a, int b, int c)
printf("%d %d %dn",
a, b, c);
}
void main()
{
foo(0);
foo(0, 10);
foo(0, 10, 100);
}
Set default value
Use b, c as default value
No default value
Use b, c as default value
0 1 2
0 10 2
0 10 100
Command prompt
82
83.
void foo(int a,int b = 1, int c )
{
printf("%d %d %dn", a, b, c);
}
Default parameters (cont.)
ERROR
error C2548: 'foo' : missing default
parameter for parameter 3
When a parameter is set default value, the
rest of next parameters MUST BE set
default value too
RULES
83
84.
Variable number of
parameters
#include<cstdio>
#include <cstdarg>
int sum(int num_param, ... )
{
int sum = 0, val = 0;
va_list marker;
va_start(marker, num_param);
for (register int i = 0; i < num_param; i++)
{
val = va_arg(marker, int);
sum += val;
}
va_end(marker);
return sum;
}
void main()
{
printf("%dn", sum(1, 10));
printf("%dn", sum(3, 1, 2, 3));
}
84
Parameter classification
Pass-by-value
A copyof parameter is made
Value parameter
Reference parameter
Constant parameter
Const Reference
parameter
Pointer parameter
void foo(int n)
{
n++;
}
void main()
{
int x = 2;
foo(x);
printf("%dn", x);
}
x = 2
2x
2x
2n
2x
3n
2x
foo
86
87.
Parameter classification
Pass-by-reference
Actually parameteritself is passed
Use reference operator “&”
Value parameter
Reference parameter
Constant parameter
Const Reference
parameter
Pointer parameter
void foo(int &n)
{
n++;
}
void main()
{
int x = 2;
foo(x);
printf("%dn", x);
}
x = 3
2x 2
x
n
x
3
n
3x
foo
87
88.
Parameter classification
Pass-by-value
A copyof parameter is made and
strict as const.
Value parameter
Reference parameter
Constant parameter
Const Reference
parameter
Pointer parameter
void foo(int const n)
{
n++;
}
void main()
{
int x = 2;
foo(x);
printf("%dn", x);
}
Fail, can not
modified
const value
2x
2x
2n
2x
3n
foo 88
89.
Parameter classification
Pass-by-ref
Actually parameter itself is passed but
avoid modify
Void the overhead of creating a copy
Value parameter
Reference parameter
Constant parameter
Const Reference
parameter
Pointer parameter
void foo(int const &n)
{
//todo
}
89
90.
Parameter classification
In common,Pass-by-value
A copy of parameter is made
Value of parameter is an address of a
memory block
Value parameter
Reference parameter
Constant parameter
Const Reference
parameter
Pointer parameter
void foo(int *n)
{
//todo
}
Value of parameter will not be
change,
but memory block which pointed
by parameter could be modified.
90
91.
Pointer Parameter
#include <cstdio>
voidfoo(int *A, int *B)
{
int *tmp = A;
A = B;
B = tmp;
}
void main()
{
int A[] = {1, 2, 3};
int B[] = {10, 11};
printf("0x%x 0x%xn", A, B);
foo(A, B);
printf("0x%x 0x%xn", A, B);
}
A’
B’
A’
B’
A
B
A
B
Copy value
(addr. of data)
foo
0x29faa8 0x29faa0
0x29faa8 0x29faa0
Command prompt
91
92.
Pointer Parameter
#include <cstdio>
voidfoo(int *A)
{
A[2] = 10;
}
void main()
{
int A[] = {1, 2, 3};
printf(“%dn", A[2]);
foo(A);
printf(“%dn", A[2]);
}
A’
A
foo
1
2
3A’[2] = 10 10
A
A[2] = 3
A[2] = 10
Copy value
(addr. of data)
92
93.
Pointer reference parameter
A special case of pointer parameter
Value of pointer parameter (address of block memory) could be changed
Pass-by-reference
CAN NOT work with array directly
#include <cstdio>
void foo(int *&A, int *&B)
{
int *tmp = A; A = B; B = tmp;
}
void main()
{
int arr1[] = {1, 2, 3};
int arr2[] = {10, 11};
int *A = arr1;
int *B = arr2;
printf("0x%x 0x%xn", A, B);
foo(A, B);
printf("0x%x 0x%xn", A, B);
}
A
B
A
B
A
B
A
B
foo
0x31fc90 0x31fc88
0x31fc88 0x31fc90
Command prompt
93
94.
Function overloading
C++ only
Allowmultiple functions with the same name, so long
as they have different parameters.
void Todo(int a)
{}
void Todo(int a, int b)
{}
94
95.
Function Prototype
In C/C++,functions MUST BE declare before using.
To solve this problems
• Keep all functions in correct order
• Use prototype inside .cpp file
• Use prototype inside header (.h) file -> recommend
#include "header.h"
void Todo1()
{
Todo2();
}
void Todo2(){}
int main(){}
Main.cpp
void Todo1()
{
Todo2();
}
void Todo2()
{}
int main()
{}
Error
error C3861:
'Todo2': identifier
not found
Main.cpp
header.h
void Todo1();
void Todo2();
95
96.
Extern function
Sometimes, weneed to use a function in another
module (.cpp file)
Header file is too complicated to use (caused error
when used)
#include <cstdio>
extern void TodoExtern();
int main()
{
TodoExtern();
return 1;
}
Main.cpp
#include <cstdio>
void TodoExtern()
{
printf("TodoExternn");
}
Extern.cpp
96
97.
Extern “C”
Name mangling:
•Aka “name decoration”
• The way of encoding additional information in a name of
function, struct, class…
In C++:
• For adapting overload, class/struct functions, name of
function will be “encoding”
int f (void) { return 1; }
int f (int) { return 0; }
int __f_v (void) { return 1; }
int __f_i (int) { return 0; }
97
98.
Extern “C”
Formixing “C” and “C++” source (Object C also) use extern "C"
Extern “C” talk to compiler that use C style for its scope
• No “name mangling”
• No overloading
Extern “C” is also “extern” function could be implement in another module
#include <stdio.h>
void ExternC()
{
printf("ExternCn");
}
Ansi_c.c
extern "C"
{
void ExternC();
void Todo()
{
printf("%d", i);
}
}
C_plusplus.cpp
98
99.
Extern “C” inpractice
#ifdef __cplusplus
extern "C" {
#endif
// your code here
#ifdef __cplusplus
}
#endif
__cplusplus: default C++ preprocessor definition
99
100.
Pointer to function
Avariable store address of a function
Advantage
• Flexible
• User for event handling mechanism
// C
void DoIt (float a, char b, char c){……}
void (*pt2Function)(float, char, char) = DoIt;
// using
pt2Function(0, 0, 0);
100
Editor's Notes
#5 New type definition
Pass-by-value vs. pass-by-reference
Size of