c/c++ tutorial csu480. who is the ta? name: jingjing duan office hours: (might change) tue & fri...

63
C/C++ Tutorial CSU480 CSU480

Post on 21-Dec-2015

219 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

C/C++ Tutorial

CSU480CSU480

Page 2: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Who is the TA?

Name: Jingjing DuanName: Jingjing Duan

Office Hours: (might change)Office Hours: (might change)

Tue & Tue & FriFri 2:00-4:00 2:00-4:00

Office: Room 266, WVHOffice: Room 266, WVH

Email: Email: [email protected]@ccs.neu.edu

Class web: www.ccs.neu.edu/course/csu480Class web: www.ccs.neu.edu/course/csu480

Page 3: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Outline

““Hello World" ProgramHello World" Program Data Types & VariablesData Types & Variables printf()printf() Arithmetic & Logical Arithmetic & Logical

Operations Operations Conditionals Conditionals LoopsLoops Arrays & StringsArrays & Strings

PointersPointers FunctionsFunctions Command-Line ArgumentCommand-Line Argument Data Structure Data Structure Memory AllocationMemory Allocation Programming TipsProgramming Tips C C vvs. C++s. C++ Books recommendedBooks recommended

Page 4: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Hello World Program

The source codeThe source code

#include <stdio.h> #include <stdio.h>

int main() int main()

{ {

printf("Hello World\n"); printf("Hello World\n");

return(0); return(0);

}}

Page 5: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Hello World Program

How to compile?How to compile?$ $ gcc hello.c –o hellogcc hello.c –o hello

gccgcc compiling commandcompiling command

hello.chello.c source filesource file

hellohello compiler-generated executable filecompiler-generated executable file

Note: the default output filename is “Note: the default output filename is “a.outa.out””

Page 6: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

How to executeHow to execute??

./hello./hello

““./ ” indicates the following file “hello” resides under the ./ ” indicates the following file “hello” resides under the

current directory. current directory.

Hello World Program

Q: why “.” is not included in $PATH Q: why “.” is not included in $PATH environment variable?environment variable?

Page 7: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Hello World Program

A: security consideration.A: security consideration.

CommandCommand LocationLocation CommentComment

lsls /bin/ls/bin/ls provided by the provided by the systemsystem

lsls current directorycurrent directory virusvirus

Page 8: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

NameName DescriptionDescription Size*Size* Range*Range*

charchar Character or small Character or small integerinteger

1 byte1 byte signed: -128 to 127signed: -128 to 127unsigned: 0 to 255 unsigned: 0 to 255

short intshort int

(short)(short)

Short integerShort integer 2 bytes2 bytes signed: -32768 to 32767signed: -32768 to 32767unsigned: 0 to 65535 unsigned: 0 to 65535

intint IntegerInteger 4 bytes4 bytes signed: -2147483648 to signed: -2147483648 to 21474836472147483647unsigned: 0 to 4294967295 unsigned: 0 to 4294967295

long intlong int

(long)(long)

Long integerLong integer 4 bytes4 bytes signed: -2147483648 to signed: -2147483648 to 21474836472147483647unsigned: 0 to 4294967295unsigned: 0 to 4294967295

floatfloat Floating point Floating point numbernumber

4 bytes4 bytes 3.4e +/- 38 (7 digits) 3.4e +/- 38 (7 digits)

doubledouble Double precision Double precision floating point numberfloating point number

8 bytes8 bytes 1.7e +/- 308 (15 digits) 1.7e +/- 308 (15 digits)

long long doubledouble

Long double Long double precision floating precision floating point numberpoint number

8 bytes8 bytes 1.7e +/- 308 (15 digits) 1.7e +/- 308 (15 digits)

Data types

Page 9: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Variable DeclarationVariable Declarationintint length = 100; length = 100; charchar num = ‘9’; //The actual value is 57 num = ‘9’; //The actual value is 57floatfloat deposit = 240.5; deposit = 240.5;unsigned shortunsigned short ID = 0x5544; ID = 0x5544;

Try the following statements, and see what happensTry the following statements, and see what happensunsigned charunsigned char value = -1; value = -1;printf(“The value is %d \n”, value);printf(“The value is %d \n”, value);

unsignedunsigned charchar value = 300; value = 300;printf(“The value is %d \n”, value);printf(“The value is %d \n”, value);

Page 10: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Result

DefinitionDefinition Memory layoutMemory layout DisplayDisplay commentcomment

unsigned char unsigned char value = -1value = -1

1111111111111111 255255

unsigned char unsigned char value = 300value = 300

0010110000101100 4444 overflowoverflow

Page 11: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Local variableLocal variable

Local variables are declared within the body of a function, and can Local variables are declared within the body of a function, and can only be used within that function.only be used within that function.

Static variableStatic variable

Another class of local variable is the static type. It is specified by the Another class of local variable is the static type. It is specified by the keyword keyword staticstatic in the variable declaration. in the variable declaration.

The most striking difference from a non-static local variable is, a static The most striking difference from a non-static local variable is, a static variable is not destroyed on exit from the function. variable is not destroyed on exit from the function.

Global variable Global variable

A global variable declaration looks normal, but is located outside any A global variable declaration looks normal, but is located outside any of the program's functions. So it is accessible to all functions.of the program's functions. So it is accessible to all functions.

Variable types

Page 12: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

An exampleAn example

int global = 10;int global = 10; //global variable//global variable

int func (int x)int func (int x)

{{

static int stat_var;static int stat_var; //static local variable//static local variable

int temp;int temp; //(normal) local variable//(normal) local variable

int name[50];int name[50]; //(normal) local variable//(normal) local variable

…………

}}

Page 13: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Variable Definition vs Declaration

DefinitionDefinition Tell the compiler about the variable: its type Tell the compiler about the variable: its type and name, as well as allocated a memory cell for and name, as well as allocated a memory cell for the variablethe variable

DeclarationDeclaration DDescribe information ``about'' the variableescribe information ``about'' the variable, , doesn’tdoesn’t allocate memory cell for the variable allocate memory cell for the variable

Page 14: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

http://www-ee.eng.hawaii.edu/~tep/EE150/book/chap14/subsection2.1.1.4.html

Page 15: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

printf()

The printf() function can be instructed to print The printf() function can be instructed to print integers, floats and string properly. integers, floats and string properly.

The general syntax isThe general syntax is printfprintf( “format”, variables);( “format”, variables);

An exampleAn exampleintint stud_id = 5200; stud_id = 5200;char * name = “Mike”;char * name = “Mike”;printfprintf(“(“%s%s ‘s ID is ‘s ID is %d%d \n”, name, stud_id); \n”, name, stud_id);

Page 16: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Format IdentifiersFormat Identifiers

%d %d decimal integersdecimal integers

%x%x hex integerhex integer

%c %c charactercharacter

%f%f float and double numberfloat and double number

%s%s stringstring

%p%p pointerpointer

How to specify display space for a variableHow to specify display space for a variable??

printf(“The student id is %printf(“The student id is %55d \n”, stud_id); d \n”, stud_id);

The value of stud_id will occupy The value of stud_id will occupy 55 characters space in the characters space in the print-out.print-out.

Page 17: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Why “\n”Why “\n”

It introduces a new line on the terminal screen.It introduces a new line on the terminal screen.

\a\a alert (bell) character alert (bell) character \\\\ backslash backslash

\b\b backspace backspace \?\? question mark question mark

\f\f formfeedformfeed \’\’ single quote single quote

\n\n newlinenewline \”\” double quote double quote

\r\r carriage returncarriage return \000\000 octal number octal number

\t\t horizontal tab horizontal tab \xhh\xhh hexadecimal number hexadecimal number

\v\v vertical tab vertical tab

escape sequence

Page 18: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Arithmetic Operations

Page 19: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Arithmetic Assignment Operators

Page 20: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Increment and Decrement Operators

awkwardawkward easyeasy easiesteasiest

x = x+1;x = x+1; x += 1x += 1 x++x++

x = x-1;x = x-1; x -= 1x -= 1 x--x--

Page 21: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Example

Arithmetic operatorsArithmetic operatorsint i = 10;int i = 10;int j = 15;int j = 15;int add = i + j;int add = i + j; //25 //25int diff = j – i;int diff = j – i; //5 //5int product = i * j;int product = i * j; // 150 // 150int quotient = j / i;int quotient = j / i; // 1 // 1int residual = j % int residual = j % i; // 5i; // 5i++;i++; //Increase by 1//Increase by 1i--;i--; //Decrease by 1//Decrease by 1

Page 22: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Comparing themComparing them

int i = 10;int i = 10;

int j = 15;int j = 15;

float k = 15.0;float k = 15.0;

j / i = ?j / i = ?

j % i = ?j % i = ?

k / i = ?k / i = ?

k % i = ? k % i = ?

Page 23: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

The AnswerThe Answer

j /j / i i = 1; = 1;

j % i = 5;j % i = 5;

k / i k / i = 1.5;= 1.5;

k % i It is k % i It is illegalillegal..

Note: For %, the operands can only be integers.Note: For %, the operands can only be integers.

Page 24: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Logical Operations

What is “true” and “false” in CWhat is “true” and “false” in C

In C, there is no specific data type to represent “true” and “false”. C In C, there is no specific data type to represent “true” and “false”. C uses value “0” to represent “false”, and uses non-zero value to stand uses value “0” to represent “false”, and uses non-zero value to stand for “true”. for “true”.

Logical OperatorsLogical Operators

A && BA && B =>=> A and BA and B

A || BA || B => => A or BA or B

A == BA == B =>=> Is A equal to B?Is A equal to B?

A != BA != B => Is A not equal to B?=> Is A not equal to B?

Page 25: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

A > BA > B =>=> Is A greater than B?Is A greater than B?

A >= B A >= B => Is A greater than or equal to B?=> Is A greater than or equal to B?

A < BA < B =>=> Is A less than B?Is A less than B?

A <= B A <= B => Is A less than or equal to B?=> Is A less than or equal to B?

Don’t be confusedDon’t be confused

&& and || have different meanings from & and |.&& and || have different meanings from & and |.

& and | are & and | are bitwisebitwise operators. operators.

Page 26: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Short circuiting

SShort circuiting means that we don't hort circuiting means that we don't evaluate the second part of an AND or OR evaluate the second part of an AND or OR unless we really need tounless we really need to..

Some practicesSome practices

Please compute the value of the following Please compute the value of the following logical expressions? logical expressions?

Page 27: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

int i = 10; int j = 15; int k = 15; int m = 0;int i = 10; int j = 15; int k = 15; int m = 0;

if( i < j && j < k) =>if( i < j && j < k) =>

if( i != j || k < j) =>if( i != j || k < j) =>

if( j<= k || i > k) =>if( j<= k || i > k) =>

if( j == k && m) =>if( j == k && m) =>

if(i)if(i) => =>

if(m || j && i )if(m || j && i ) => =>

Page 28: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

int i = 10; int j = 15; int k = 15; int m = 0;int i = 10; int j = 15; int k = 15; int m = 0;

if( i < j && j < k) => if( i < j && j < k) => falsefalse

if( i != j || k < j) => if( i != j || k < j) => truetrue

if( j<= k || i > k) => if( j<= k || i > k) => truetrue

if( j == k && m) => if( j == k && m) => falsefalse

if(i)if(i) => => truetrue

if(m || j && i )if(m || j && i ) => => truetrue

Did you get the correct answers? Did you get the correct answers?

Page 29: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Conditionals

if statement if statement Three basic formats,Three basic formats,ifif ( (expressionexpression){ ){

statement …statement …}}ifif ( (expressionexpression) {) {

statement …statement … }}elseelse{ {

statement …statement … } }

Page 30: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

if (if (expressionexpression) {) {

statement…statement…

}} else ifelse if ( (expressionexpression) {) {

statement…statement…

}} else{else{

statement…statement…

}}

Page 31: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

An exampleAn example

if(score >= 90){if(score >= 90){

a_cnt ++;a_cnt ++;

}else if(score >= 80){}else if(score >= 80){

b_cnt++;b_cnt++;

}else if(score >= 70){}else if(score >= 70){

c_cnt++;c_cnt++;

}else if (score>= 60){}else if (score>= 60){

d_cnt++d_cnt++

}else{}else{

f_cnt++f_cnt++

}}

Page 32: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

The switch statementThe switch statementswitch (switch (expressionexpression) ) { {

case case item1item1: : statementstatement; ; break; break;

case case item2item2: : statementstatement; ; break; break;

default: default: statementstatement; ; break; break;

} }

Page 33: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Loops

for statementfor statement

for (for (expression1expression1; ; expression2expression2; ; expression3expression3)){{

statement…statement…

}}

expression1expression1 initializes; initializes;

expression2expression2 is the terminate test; is the terminate test;

expression3expression3 is the modifier is the modifier;;

Page 34: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

An exampleAn example

int x;int x;

for (x=0; x<3; x++) for (x=0; x<3; x++)

{ {

printf("x=%d\n",x); printf("x=%d\n",x);

} }

First time: First time: x = 0;x = 0;

Second time:Second time: x = 1;x = 1;

Third time: Third time: x = 2;x = 2;

Fourth time:Fourth time: x = 3; (don’t execute the body)x = 3; (don’t execute the body)

Page 35: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

The while statementThe while statementwhile (while (expressionexpression) {) {

statementstatement … …}}while loop exits only when the expression is while loop exits only when the expression is false. false.

An exampleAn exampleint x = 3; int x = 3; while (x>0) { while (x>0) {

printf("x=%d n",x); printf("x=%d n",x); x--; x--;

} }

Page 36: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

for <==> while

for (for (expression1expression1; ; expression2expression2; ; expression3expression3)){{

statement…statement…

}}

expression1;expression1;

while (expression2)while (expression2)

{{

statement…;statement…;

expression3;expression3;

}}

equals

Page 37: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Arrays & Strings

Arrays Arrays int ids[50];int ids[50];char name[100];char name[100];int table_of_num[30][40];int table_of_num[30][40];

Accessing an arrayAccessing an array

ids[0] = 40;ids[0] = 40;

i = ids[1] + j;i = ids[1] + j;table_of_num[3][4] = 100;table_of_num[3][4] = 100;Note: In C Array subscripts start at Note: In C Array subscripts start at 00 and end one less than and end one less than the array size.the array size. [0 .. n-1][0 .. n-1]

Page 38: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

StringsStrings

Strings are defined as arrays of characters.Strings are defined as arrays of characters.

The only difference from a character array is, a symbol “\0” The only difference from a character array is, a symbol “\0” is used to indicate the end of a string. is used to indicate the end of a string.

For example, suppose we have a character array, char For example, suppose we have a character array, char name[8], and we store into it a string “Dave”.name[8], and we store into it a string “Dave”.

Note: the length of this string 4, but it occupies 5 bytes.Note: the length of this string 4, but it occupies 5 bytes.

DD aa vv ee \0\0

Page 39: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Functions

Functions are easy to use; they allow complicated programs to be broken Functions are easy to use; they allow complicated programs to be broken into small blocks, each of which is easier to write, read, and maintain.into small blocks, each of which is easier to write, read, and maintain. This is called This is called modulationmodulation..

How does a function look likeHow does a function look like??

returntype returntype function_name(function_name(parameters…parameters…)     )    

{   {  

locallocal variables declaration;variables declaration;    

functionfunction code;code;

return result;   return result;  

} }

Page 40: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Sample functionSample function

int addition(int x, int y)int addition(int x, int y)

{{

int add;int add;

add = x + y;add = x + y;

return add;return add;

} } How to How to call a function?call a function?

int result;int result;

int i = 5, j = 6; int i = 5, j = 6;

result = addition(i, j);result = addition(i, j);

Page 41: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Pointers

Pointer is the most beautifulPointer is the most beautiful ( (ugliestugliest)) part of C, but also part of C, but also brings most trouble to C programmers. Over 90% bugs in brings most trouble to C programmers. Over 90% bugs in the C programs come from pointers.the C programs come from pointers.

““The International Obfuscated C Code ContestThe International Obfuscated C Code Contest ””((http://www.ioccc.org/http://www.ioccc.org/))

What is a pointerWhat is a pointer??A pointer is a variable which contains the address in memory A pointer is a variable which contains the address in memory

of another variable. of another variable.

In C we have a specific type for pointers.In C we have a specific type for pointers.

Page 42: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Declaring a pointer variableDeclaring a pointer variable

int * pointer;int * pointer;

char * name; char * name; How to obtain the How to obtain the addressaddress of a variable of a variable??

int x = 0x2233;int x = 0x2233;

pointer = &x; pointer = &x;

where & is called where & is called address ofaddress of operator. operator.

How to get the How to get the valuevalue of the variable indicated by the of the variable indicated by the pointerpointer??

int y = *pointer; int y = *pointer;

Page 43: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

3333 2222 0000 0000

0x5200 0x5203

0x5200

pointer

What happens in the memory?

Suppose the address of variable x is 0x5200 in the above example, so the value of the variable pointer is 0x5200.

X

Page 44: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

swap the value of two variables

Page 45: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Why is the left one not working?

swap

main

x, y

a, b

call swap(a, b) in main

x, y, a, b are all local variables

Page 46: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Why is the right one working?

Page 47: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Pointers and ArraysPointers and Arrays

Pointers and arrays are very closely linked in C. Pointers and arrays are very closely linked in C.

Array elements arranged in Array elements arranged in consecutiveconsecutive memory locations memory locations

Accessing array elements using pointersAccessing array elements using pointers

int ids[50];int ids[50];

int * p = &ids[0];int * p = &ids[0];

p[i] p[i] <<=>=> ids[i] ids[i]

Pointers and StringsPointers and Strings

A string can be represented by a A string can be represented by a char *char * pointer. pointer.

Page 48: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Char name[50];Char name[50];

name[0] = ‘D’;name[0] = ‘D’;

name[1] = ‘a’;name[1] = ‘a’;

name[2] = ‘v’;name[2] = ‘v’;

name[3] = ‘e’;name[3] = ‘e’;

name[4] = ‘\0’;name[4] = ‘\0’;

char * p = &name[0];char * p = &name[0];

printf(“The name is %s \n”, p);printf(“The name is %s \n”, p);

NNootete: The : The pp represents the string “Dave”, but not the array represents the string “Dave”, but not the array

name[50]. name[50].

Page 49: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Command-Line Argument

In C you can pass arguments to main() function. In C you can pass arguments to main() function. mmain() prototypeain() prototype

int main(int argc, char * argv[]);int main(int argc, char * argv[]);argc indicates the number of argumentsargc indicates the number of argumentsargv is an array of input string pointers. argv is an array of input string pointers.

How to pass your own argumentsHow to pass your own arguments?? ./hello 10 ./hello 10

Page 50: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

What value is argc and argvWhat value is argc and argv??

Let’s add two printf statement to get the value of argc and Let’s add two printf statement to get the value of argc and argv.argv.

#include <stdio.h> #include <stdio.h>

int main(int main(int argc, char * argv[]);int argc, char * argv[]);) )

{ {

int i=0;int i=0;

printf("Hello World\n"); printf("Hello World\n");

printf(“The argc is %d \n”, argc);printf(“The argc is %d \n”, argc);

for(i=0; i < argc; i++){for(i=0; i < argc; i++){

printf(“The %dth element in argv is %s\n”, i, printf(“The %dth element in argv is %s\n”, i, argv[i]); argv[i]);

}}

return(0); return(0);

}}

Page 51: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

The outputThe output

The argc is 2The argc is 2

The 0th element in argv is ./helloThe 0th element in argv is ./hello

The 1th element in argv is 10The 1th element in argv is 10

The trick is the system always passes the name of the The trick is the system always passes the name of the executable file as the executable file as the firstfirst argument to the main() argument to the main() function.function.

How to use your argumentHow to use your argument?? Be careful. Your arguments to main() are always in string Be careful. Your arguments to main() are always in string

format. format.

Taking the above program for example, the argv[1] is Taking the above program for example, the argv[1] is string “10”, not a number. You must convert it into a string “10”, not a number. You must convert it into a number before you can use it. number before you can use it.

Page 52: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Data Structure

A data structure is a collection of one or more variables, possibly of A data structure is a collection of one or more variables, possibly of different types. different types.

An example of student recordAn example of student record

structstruct stud_record{ stud_record{

char name[50];char name[50];

int id;int id;

int age;int age;

int major;int major;

…………

}; };

Page 53: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

A data structure is also a data typeA data structure is also a data type

struct stud_record my_record;struct stud_record my_record;

struct stud_record * pointer;struct stud_record * pointer;

pointer = & my_record;pointer = & my_record;

Accessing a field inside a data structureAccessing a field inside a data structure

my_record.id = 10;my_record.id = 10; “.”“.”

oror

pointer->id = 10;pointer->id = 10; “->”“->”

Page 54: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Memory Allocation

Stack memory allocationStack memory allocationNon-static local variable is an example of stack memory Non-static local variable is an example of stack memory allocation. allocation. Such memory allocations are placed in a system memory Such memory allocations are placed in a system memory area called the area called the stackstack. .

Static memory allocationStatic memory allocationStatic local variable and global variable require static Static local variable and global variable require static memory allocation. Static memory allocation happens memory allocation. Static memory allocation happens before the program starts, and before the program starts, and persistspersists through the entire through the entire life time of the program.life time of the program.

Page 55: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Dynamic memory allocationDynamic memory allocation

It allows the program determine how much memory it It allows the program determine how much memory it needs needs at at run timerun time,, and allocate exactly the right amount of and allocate exactly the right amount of storage.storage.

The region of memory where dynamic allocation and The region of memory where dynamic allocation and deallocation of memory can take place is called the deallocation of memory can take place is called the heapheap..

NoteNote: the program has the responsibility to free the : the program has the responsibility to free the dynamic memory it allocated. dynamic memory it allocated.

Page 56: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Memory arrangement

Page 57: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Functions for the dynamic memory allocationFunctions for the dynamic memory allocation

void *malloc(size_t number_of_bytes);void *malloc(size_t number_of_bytes);

allocates dynamic memoryallocates dynamic memory

size_t sizeof(type); size_t sizeof(type);

returns the number of bytes of typereturns the number of bytes of type

void free(void * p)void free(void * p)

releases dynamic memory allocationreleases dynamic memory allocation

An example of dynamic memory allocationAn example of dynamic memory allocation

int * ids;int * ids; //id arrays//id arrays

int num_of_ids = 40;int num_of_ids = 40;

ids = malloc( sizeof(int) * num_of_ids); ids = malloc( sizeof(int) * num_of_ids);

………….. Processing …..... Processing …...

free(ids);free(ids);

Page 58: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Allocating a data structure instanceAllocating a data structure instancestruct stud_record * pointer;struct stud_record * pointer;pointer = malloc(pointer = malloc(sizeofsizeof(struct stud_record));(struct stud_record));pointer->id = 10;pointer->id = 10;

NeverNever calculate the size of data structure yourself. calculate the size of data structure yourself. The The reason is the size of data types is reason is the size of data types is machine-dependentmachine-dependent. . Give Give it to sizeof() functionit to sizeof() function..

ssize of intize of int

32-bytes machines32-bytes machines 3232

64-bytes machines64-bytes machines 6464

Page 59: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Programming Tips Replacing numbers in your code with macrosReplacing numbers in your code with macros

- don’t use - don’t use magic numbers magic numbers directlydirectly#define MAX_NAME_LEN #define MAX_NAME_LEN 50;50;char name[MAX_NAME_LEN];char name[MAX_NAME_LEN];

Avoiding global variables Avoiding global variables - modulation is more important- modulation is more important

Giving variables and functions a nice nameGiving variables and functions a nice name- a meaning name- a meaning name

Don’t repeat your code Don’t repeat your code - make a subroutine/function- make a subroutine/function

Don’t let the function body to exceed one screenDon’t let the function body to exceed one screen- hard to debug- hard to debug

Page 60: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Indenting your codeIndenting your code (clearance)(clearance)

if(expression)if(expression)

{{

if(expression)if(expression)

{{

…………

}}

}} Commenting your codeCommenting your code Don’t rush into coding. Plan first. Don’t rush into coding. Plan first. Printing out more debugging information Printing out more debugging information Using debugger (gdb)Using debugger (gdb)

Page 61: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

C vs. C++

C++ is a superset of CC++ is a superset of C C++ has all the characteristics of CC++ has all the characteristics of C Using g++ to compile your source codeUsing g++ to compile your source code

Page 62: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Books recommended

The C Programming LanguageThe C Programming Language, Brian Kernighan , Brian Kernighan and Dennis Ritchie. Second edition. Prentice-Hall, and Dennis Ritchie. Second edition. Prentice-Hall, 1988. 1988. (C Bible)(C Bible)

The C++ Programming LanguageThe C++ Programming Language, Bjarne , Bjarne Stroustrup. Third edition. Addison-Wesley, 1997. Stroustrup. Third edition. Addison-Wesley, 1997. (C++ Bible)(C++ Bible)

Advanced Programming in the UNIX Advanced Programming in the UNIX EnvironmentEnvironment,, W. Richard StevensW. Richard Stevens,, Addison- Addison-Wesley, 1992Wesley, 1992.. (APUE)(APUE)

Page 63: C/C++ Tutorial CSU480. Who is the TA? Name: Jingjing Duan Office Hours: (might change) Tue & Fri 2:00-4:00 Office: Room 266, WVH Email: duanjj@ccs.neu.edu

Thanks