một số kiến thức cơ bản về c.pdf
TRANSCRIPT
-
8/12/2019 Mt s Kin thc c bn v C.pdf
1/153
1
Mt s kin thc c s v lp trnhbng ngn ng C
-
8/12/2019 Mt s Kin thc c bn v C.pdf
2/153
2
CHNG 1: C S NGN NG C
I. Phn m u
Ni dung:
Giithiu ngn ng C & C++ Lp trnh hng i tng (Object oriented programming) C s v phn cng v phn mm thc hin chng trnh C.
Gii thiu ngn ng C & C++
- C l mt loi ngn ng lp trnh bc cao a dng ph bin nht hin nay. - C c pht trin t ngn ng B (K. Thompson, 1967) bi Dennis Ritchie ca hngAT&T Bell Labs v bt u xut hin t nm 1972.- Yu cu ca ngn ng bc cao: tnh d c-vit (readability), tnh d bo tr(maintainability) v kh nng linh ng (portability).C l ngn ng lp trnh c lp vi phn cng v cc h iu hnh my tnh.- 1978: quyn sch The C Programming Language(Kernighan & Ritchie) l ti liu kinhin ca ngn ng C.
- 1983: American National Standards Institute (ANSI) thnh lp y ban xy dng chuncho ngn ng C.- 1990: Chun ANSI C ra i.
- 1983: yu t lp trnh hng i tng + Cngn ng C++do Bjarne Stroustrup phttrin Bell Labs.- C++ l mt ngn ng gn nh l m rng ca ngn ng C, c 3 phin bn: 1.1(1986), 2.0 (1989) v 3.0 (1991). Chnh phin bn 3.0 l c s xy dng chun ANSIC++ .
Lp trnh hng i tng (Object Oriented Programming)
- Phng php lp trnh:* LT tuyn tnh (linear)* LT th tc (procedural)LT cu trc (structural) (Chng trnh = Cu trc d
liu + Gii thut)* LT hng i tng (object-oriented)
-
8/12/2019 Mt s Kin thc c bn v C.pdf
3/153
3
- c im LTHT:*i tng(Object): D liu + phng thctrng tm ca qu trnh pht trin
chng trnh.*Lp(Class): tp hp cc i tng c tnh cht chung ging nhau.* Tnh ng gi d liu(encapsulation): i tng bao gm d liu v phng
thc c ng gi m ngi s dng c th tip cn n d liu thng qua cc chcnng m khng cn bit n ni dung lp trnh c th ca chng.* Tnh k tha(inheritance): S k tha cho php nh ngha cc lp mi da trn
cc lp c sncho php s dng li cc module chng trnh m khng cn thay ichng.
* Tnh a hnh(polymorphism): trong cc lp k tha nhau, c th nh nghaphng thc c cng tn hoc ngha nhng hon ton khc nhau v mt lp trnh.
- u im:* Tnh k thaloi b nhng on chng trnh phi vit li, m rng cc lp
nhanh chng.
* C s chng trnh l i tng
vic thit k v lp trnh thc hin theo quytrnh ch khng theo kinh nghim hoc th thut tit kim thi gian v tng nng sut.* Tnh ng gim bo tnh bo mt m vn pht trin chng trnh c.* Cch tip cn t trng tm i tngc th xy dng m hnh chi tit v d
ci t.* Kh nng m rng h thng ln hn kh thi hn.
- Ngn ng LTHT:
C s v phn cng v phn mm thc hin chng trnh C
Phn cng:* Cc loi my tnh c phn mm bin dch ngn ng C &C++ (tng thch ANSI
SIMULA (66)
SMALLTALK
SMALLTALK
JAVA (95)
ADA (83)
ADA (95)
EIFFEL (90)
C++ (86)
-
8/12/2019 Mt s Kin thc c bn v C.pdf
4/153
4
C)* i vi PC, cu hnh my ph hp vi chng trnh bin dch ngn ng.
Phn mm:* Cc loi my s dng HH Unix, C l ngn ng mc nh.
* i vi PC: Turbo C, Turbo C++, Borland C++, Symantec C, Visual C++, C++Builder
II. Chng trnh C u tin
Ni dung:
Vi phn ny ta lm quen vi cu trc ca mt chng trnh C v cc thnh phn cu tonn n:
Ch thch Ch th #include Tp Header Hm main() Lnh return Hm exit() Kiu d liu void Bin dch v kt ni D sa li
V d n gin chng trnh C
1: / * Chuong t r i nh dau t i en */2: #i ncl ude 3:4: mai n( )5: {6: pr i nt f ( "Chao ban! Day l a chuong t r i nh C dau t i en cua t oi . \ n") ;7: r et ur n 0;8: }
Ch thch
Trong ngn ng C, hng ch thch c gii hn gia hai du /* v */. Trnh phin dchC s b qua tt c ni dung cha trong cp du trn.
/ * Chuong t r i nh dau t i en */
-
8/12/2019 Mt s Kin thc c bn v C.pdf
5/153
5
i vi C++, ta c th s dng // u mi hng ch thch.
/ *Thi s comment does not i ncr ease t he si ze oft he execut abl e f i l e ( bi nar y code) , nor doesi t af f ect t he per f or mance speed.
*/
Tng ng vi:
/ / Thi s comment does not i ncrease the si ze of/ / t he execut abl e f i l e ( bi nar y code) , nor does/ / i t af f ect t he per f or mance speed.
Ch : Cc on ch thch khng c php lng vo nhau.
Ch th #include
#i ncl ude
Ch th #includec tc dng bo b tin x l C tm tptin ng vi ni dung vchp ni dung tp tin vo v tr ca include trong chng trnh. Cc tp tn ng vi nidung trong < > thng l cc tp tin headerng vi nhng hm thng dng trong thvin ca C, thng nm trong th mc INCLUDE\. Nu cc tp header nm ti th mclm vic, ta dng ngoc kp thay cho ngoc < >.
Ch : Ngn ng C phn bit ch Hoa v ch thng !!!
Hm main()
Hm main() hng 4 l hm c bit trong C. Mi chng trnh C phi c hm ny vchy chng trnh bt u t hm ny. Ni dung cc dng lnh trong hm nm giangoc { }.
Trong hm c lnh c bit returnc nhim v tr li mt gi tr no cho hm. Mcnh n tr li mt gi tr s nguyn (int). Hng 5 tr li gi tr 0, ngha l chng trnhkt thc bnh thng; nu gi tr tr li khc 0, iu ngha l chng trnh kt thc cli.
Hm exit(), hm c s ca th vin C c nh ngha trong tp header stdlib.h (khimun dng hm ny, phi gi #i ncl ude ), dng kt thc chng trnh,nhng khng tr li gi tr no c.
V d:1: / * Chuong t r i nh dau t i en */2: #i ncl ude 3: #i ncl ude 4: voi d mai n( )
-
8/12/2019 Mt s Kin thc c bn v C.pdf
6/153
6
5: {6: pr i nt f ( "Chao ban! Day l a chuong t r i nh C dau t i en cua t oi . \ n") ;7: exi t (0) ;8: }
Trong chng trnh trn, hng 4 c thm t kha void xc nh kiu d
liu trng (empty). Nu void c thm vo trc tn hm, hm s khngphi tr li mt gi tr no c. Trong trng hp trn, v hm exit(0) khngtr gi tr, t void phi c thm hng 4.
Bin dch v kt ni (compiling and linking)
Li chng trnh v d sa li (debugging)
Khi chng trnh ngun c dch v kt ni, c th xut hin nhng li c php, li ktni m ta cn phi sa li cho ng trc khi chng trnh c dch thnh dng thihnh c (executable).
Cc chng trnh thng cung cp cho ngi s dng cng c d sa li (debugger).
Sinh vin nn tp lm quen vi cng c ny nng cao hiu qu lp trnh.
III. Cc thnh phn c s ca chng trnh C
Ni dung:
Vi phn ny ta lm quen vi cc thnh phn c s cu to nn ngn ng C:
Hng v bin Biu thc Cu lnh Cm cu lnh Cu trc hm Kiu v tn hm i s ca hm Cch gi hm
Program.c Program.obj Program.exe
BIEN DICH(kiem tra cu phap,
KET NOI(ket noi cac modul thu vien,)
-
8/12/2019 Mt s Kin thc c bn v C.pdf
7/153
7
Cc thnh phn c s
Hng v bin
Hng l i lng khng thay i gi tr trong qu trnh thi hnh chng trnh.Bin l i lng m gi tr ca n c th thay i trong qu trnh thi hnh chng trnh.
Biu thc
Biu thc l t hp cc hng, bin v cc ton t xc nh cc php ton.
( 2 + 3*i ) / 10
Ton t s hc
K hiu ngha+ Cng- Tr* Nhn/ Chia% Phn d (modulo)
Cu lnh
Cu lnh l mt t hp c ngha ( 2 v) cc biu thc v chm dt bi duchm phy (;).i = ( 2 + 3) * 10;i = 2 + 3 * 10;
j = 6 % 4;k = i + j ;
r et ur n 0;exi t ( 0) ;pr i nt f ( "Ket t huc chuong t r i nh") ;
Cm cu lnh
Cm cu lnh l nhm cu lnh bt u bng ngoc { v kt thc bng ngoc }. Cmculnh c thi hnh nh mt cu lnh bi b bin dch C.
f or ( . . . ) {s3 = s1 + s2;mul = s3 * c;r emai nder = sum % c;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
8/153
8
}
Cu trc mt hm C
Mt hm c cu to bi 6 phn:
- Kiu hm- Tn hm- i s- Ngoc m {- Thn hm- Ngoc ng }
Kiu hm l kiu d liu m hm s tr. Mc nh hm tr kiu int. Kiu void se khngtr gi g no c.Tn hm phi c ngha v ng c php.
Tn khng ng C php2 (digit) Tn hm khng c khi u bng s* (Asterisk) Tn hm khng ckhi u bng du+ (Addition) Tn hm khng c khi u bng t kha. (dot) Tn hm khng c khi u bng .total-number Tn hm khng c cha k hiu ton taccount'97 Tn hm khng c cha du
Tn hp l: print2copy, total_number,_quick_add, Method3
i s hm C
i s l nhng bin nm trong ngoc n sau tn hm. i s hm C ch c tnh thamtr, ngha l n ch truyn gi tr vo trong hm ch khng thay i gi tr ngoi hm.
V d: Hm cng 2 s nguyn1: / * Thi s f unct i on adds t wo i nt eger s and r et ur ns t he r esul t */2: i nt i nt eger _add( i nt x, i nt y )3: {4: i nt resul t ;5: r esul t = x + y;
6: r et ur n r esul t ;7: }
Li khuynKhng nn to hm qu phc tp v di, mnn chia nh (to nhiu hm con) ra ddng theo di trong qu trnh iu chnh hoc s li chng trnh.
Cch gi hm
-
8/12/2019 Mt s Kin thc c bn v C.pdf
9/153
9
V d: Chng trnh tnh php cng v xut gi tr ln mn nh1: / * Cal cul at e an addi t i on and pr i nt out t he r esul t */2: #i ncl ude 3: / * Thi s f unct i on adds two i nt eger s and r et ur ns the r esul t * /4: i nt i nt eger _add( i nt x, i nt y )5: {
6: i nt resul t ;7: r esul t = x + y;8: r et ur n r esul t ;9: }10:11: i nt mai n( )12: {13: i nt sum;14:15: sum = i nt eger _add( 5, 12) ;16: pr i nt f ( "The addi t i on of 5 and 12 i s %d. \ n", sum) ;17: r et ur n 0;18: }
Bi tp
1. Vit mt hm C nhn 2 s nguyn vi nhau v tr li gi tr nhn.2. Vit chng trnh gi hm nhn BT1 nhn 3 vi 5 v xut kt qu ln mn
nh.
IV. Kiu v tn d liu trong C
Ni dung:
Vi phn ny ta lm quen vi cc bn kiu d liu c s cangn ng C:
char int float double
T kha
T kha l t dnh ring xc nh mt c trng ca ngn ng, khng c dng lmbin, hng hoc tn hm. ANSI C c 32 t kha sau (v ch vit bng ch thng !!):
Keyword Description Keyword Description
auto Storage class specifier int Type specifier
-
8/12/2019 Mt s Kin thc c bn v C.pdf
10/153
10
break Statement long Type specifiercase Statement register Storage class specifierchar Type specifier return Statementconst Storage class modifier short Type specifier
continue Statement signed Type specifierdefault Label sizeof Operatordo Statement static Storage class specifier
double Type specifier struct Type specifierelse Statement switch Statementenum Type specifier typedef Statementextern Storage class specifier union Type specifierfloat Type specifier unsigned Type specifier
for Statement void Type specifiergoto Statement volatile Storage class modifierif Statement while Statement
Kiu d liu char
Mt i tng ca kiu charbiu th mt k t n ng vi bng m k t 8 bits ASCII.
Bin k tchar variablename;
hoc:
char variablename1, variablename2, variablename3;
Format K t: %c
Hng k tx = A' ;x = 65;
hoc
x = `a' ;x = 97;
K t that (\)
K tM t\b BACKSPACE\f Kt thc trang (form-feed)
-
8/12/2019 Mt s Kin thc c bn v C.pdf
11/153
11
\r Xung hng (RETURN)\t TAB
Xut cc k t
Dng hm printf(), nhnghi4a trong stdio.h, xut ln mn nh.
V d: In cc k t ln mn nh.
1: / * Pr i nt i ng out char acters */2: #i ncl ude 3:4: mai n( )5: {6: char c1;7: char c2;8:
9: c1 = `A' ;10: c2 = `a' ;11: pr i nt f ( "Conver t the val ue of c1 t o char act er : %c. \ n", c1) ;12: pr i nt f ( "Conver t the val ue of c2 t o char act er : %c. \ n", c2) ;13: r et ur n 0;14: }
Kt qu:
Conver t t he val ue of c1 t o charact er : A.Conver t t he val ue of c2 t o charact er : a.
V d: Bin i s thnh k t (dng format %c)1: / * Conver t i ng numeri c val ues back t o charact ers */2: #i ncl ude 3:4: mai n( )5: {6: char c1;7: char c2;8:9: c1 = 65;10: c2 = 97;11: pr i nt f ( "The charact er that has t he numer i c val ue of 65 i s:%c. \ n", c1) ;12: pr i nt f ( "The charact er that has t he numer i c val ue of 97 i s:
%c. \ n", c2) ;13: r et ur n 0;14: }
Kt qu:
The char act er t hat has t he numer i c val ue of 65 i s: A.The char act er t hat has t he numer i c val ue of 97 i s: a.
-
8/12/2019 Mt s Kin thc c bn v C.pdf
12/153
12
Kiu d liu int
D liu s khng c thnh phn thp phn. Khong ln ca n ph thuc vo di bnh lu tr.
S nguyn 32 bits : t 2147483647 (231
_1) n -2147483648.S nguyn 16 bits : t 32767 (215_1) n -32768.
Bin inti nt variablename;i nt variablename1, variablename2, variablename3;
Format int: %f
V d: Bin i k t thnh s (dng format %d)1: / * Showi ng t he numer i c val ues of charact ers */
2: #i ncl ude 3:4: mai n( )5: {6: char c1;7: char c2;8:9: c1 = `A' ;10: c2 = `a' ;11: pr i nt f ( "The numer i c val ue of A i s: %d. \ n", c1) ;12: pr i nt f ( "The numer i c val ue of a i s: %d. \ n", c2) ;13: r et ur n 0;14: }
Kt qu:The numer i c val ue of A i s: 65.The numer i c val ue of a i s: 97.
Kiu d liu float
D liu s thc biu din bng du chm ng.
S thc 32 bits: Khang gi tr +/-1.0*1037, c t nht 6 s l thp phn. Cc php tnhgi s thc v s thc hoc vi s nguyn cho kt qu kiu float.
Bin floatf l oat variablename;f l oat variablename1, variablename2, variablename3;
Format float: %f
V d: Xut kt qu chia s int v float1: / * I nt eger vs. f l oat i ng- poi nt di vi s i ons */
-
8/12/2019 Mt s Kin thc c bn v C.pdf
13/153
13
2: #i ncl ude 3:4: mai n( )5: {6: i nt i nt _num1, i nt _num2, i nt _num3; / * Decl ar e i nt eger var i abl es*/7: f l oat f l t _num1, f l t _num2, f l t _num3; / * Decl ar e f l oat i ng- poi ntvar i abl es */8:9: i nt _num1 = 32 / 10; / * Both di vi sor and di vi dend are i nt eger s*/10: f l t _num1 = 32 / 10;11: i nt _num2 = 32. 0 / 10; / * The di vi sor i s an i nt eger */12: f l t _num2 = 32. 0 / 10;13: i nt _num3 = 32 / 10. 0; / * The di vi dend i s an i nt eger */14: f l t _num3 = 32 / 10. 0;15:16: pr i nt f ( "The i nt eger di vi s. of 32/ 10 i s: %d\ n", i nt _num1) ;17: pr i nt f ( "The f l oat i ng- poi nt di vi s. of 32/ 10 i s: %f \ n", f l t _num1) ;18: pr i nt f ( "The i nt eger di vi s. of 32. 0/ 10 i s: %d\ n", i nt _num2) ;
19: pr i nt f ( "The f l oat i ng- poi nt di vi s. of 32. 0/ 10 i s: %f \ n",f l t _num2) ;20: pr i nt f ( "The i nt eger di vi s. of 32/ 10. 0 i s: %d\ n", i nt _num3) ;21: pr i nt f ( "The f l oat i ng- poi nt di vi s. of 32/ 10. 0 i s: %f \ n",f l t _num3) ;22: r et ur n 0;23: }
Kt qu:
The i nt eger di vi s. of 32/ 10 i s: 3The f l oat i ng- poi nt di vi s. of 32/ 10 i s: 3. 000000The i nt eger di vi s. of 32. 0/ 10 i s: 3
The f l oat i ng- poi nt di vi s. of 32. 0/ 10 i s: 3. 200000The i nt eger di vi s. of 32/ 10. 0 i s: 3The f l oat i ng- poi nt di vi s. of 32/ 10. 0 i s: 3. 200000
Kiu d liu double
D liu s thc c chnh xc gp i.
S thc 64 bits, c t nht 10 s l thp phn.
Bin double
doubl evariablename
;doubl e variablename1, variablename2, variablename3;
Format double: %e, %E
Quy c t tn bin
-
8/12/2019 Mt s Kin thc c bn v C.pdf
14/153
14
Cc k t sau y c dng t tn bin: A-Z, a-z, 0-9 (nhng khng c t u), dugch di (_).
Bin khng c cha k hiu ton t.Bin khng c cha du (.).
Bin khng c cha ().Bin khng c cha k hiu c bit nh *, @, #, ?, v.v..
Cnh boKhng bao gi dng t kha ca C hoc tn cc hm th vin C lm tn bin mc d cth c.
Bi tp
1. Vit chng trnh xut cc gi tr s ca cc k t Z v z..2. Vit chng trnh xut cc cc k t c gi tr s 72 and 104.3. Cho s double dbl_num= 123.456;,vit chng trnh xut gi tr trn theo format
float v doule.4. Vit chng trnh xut gi tr bng s ca k t xung hng (\n).
V. c v vit qua cc giao tip nhp xut (I/O) chun
Ni dung:
Vi phn ny ta tm hiu k hn vi lnh printf()cng nh cc lnh nhp xut sau:
Hm getc() Hm putc() Hm getchar() Hm putchar()
Cc giao tip nhp xut chun (I/O)
Ngn ng C x l mt tp tin nh mt chui byte (8 bits), gi l streamv c th thunhn hoc ghi li n qua cc giao tip xut nhp (I/O):
Ni dung Thit b giao tipStdin Giao tip nhp chun Bn phmStdout Giao tip xutchun Mn nhStderr Giao tip li thng bo li Mn nh
-
8/12/2019 Mt s Kin thc c bn v C.pdf
15/153
15
Ghi chNgn ng C thao tc vi nhiu lnh nhp xut (I/O) cha trong header stdio.h. Cho nn,lun nh khai bo #include stdio.h trc khi s dng cc lnh I/O. i vi C++, cc lnh
nhp xut cha trong iostream.h.
Giao tip nhp t ngi s dng (thng l thng qua bn phm)
Hm getc()
Hm getc() c 1 k t t mt file stream v tr li gi tr s nguyn ng vi k t .
#i ncl ude i nt get c( FI LE *st r eam) ;
Nu kt thc tp (end-of-file) hoc li xut hin, hm tr li gi tr EOF.
V d: c k t do ngi s dng cho vo1: / *Readi ng i nput by cal l i ng get c( ) */2: #i ncl ude 3:4: mai n( )5: {6: i nt ch;7:8: pr i nt f ( "Pl ease t ype i n one char acter: \ n") ;9: ch = get c( st di n ) ;
10: pr i nt f ( "The char act er you j ust ent er ed i s: %c\ n", ch) ;11: r et ur n 0;12: }
Kt qu:Pl ease t ype i n one charact er :H
The char act er you j ust entered i s: H
Hm getchar()
Hm getchar() tng ng vi getc(stdin).
#i ncl ude i nt get char ( voi d) ;
Nu kt thc tp (end-of-file) hoc li xut hin, hm tr li gi tr EOF.
V d: c k t do ngi s dng cho vo1: / *Readi ng i nput by cal l i ng get char ( ) */2: #i ncl ude 3:
-
8/12/2019 Mt s Kin thc c bn v C.pdf
16/153
16
4: mai n( )5: {6: i nt ch1, ch2;7:8: pr i nt f ( "Pl ease t ype i n t wo char acters t oget her : \ n") ;9: ch1 = get c( st di n ) ;10: ch2 = getchar( ) ;11: pr i nt f ( "The f i r st char acter you j ust ent er ed i s: %c\ n", ch1) ;12: pr i nt f ( "The second char act er you j ust ent er ed i s: %c\ n", ch2) ;13: r et ur n 0;14: }
Kt qu:Pl ease t ype i n t wo charact er s t ogether :Hi
The f i r st char act er you j ust enter ed i s: HThe second char act er you j ust enter ed i s: i
Giao tip xut ra mn nh
Hm putc()
Hm putc() ghi 1 k t vo mt file stream.
#i ncl ude i nt put c(i nt c, FI LE *st r eam) ;
Nu ghi thnh cng, hm tr li gi tr k t,; nu khng tr li EOF.
V d: Xut mt k t ln mn nh1: / *Out put t i ng a char act er wi t h put c( ) */
2: #i ncl ude 3:4: mai n( )5: {6: i nt ch;7:8: ch = 65; / * t he numer i c val ue of A */9: pr i nt f ( "The char act er t hat has numer i c val ue of 65 i s: \ n") ;10: put c(ch, st dout ) ;11: r et ur n 0;12: }
Kt qu:The char act er t hat has numer i c val ue of 65 i s:
AC: \ app>
Hm putchar()
Hm putchar() tng ng vi putc(stdout).
#i ncl ude i nt put char ( i nt c) ;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
17/153
17
Nu ghi thnh cng, hm tr li gi tr k t,; nu khng tr li EOF.
V d: Xut k t ln mn nh1: / * 05L04. c: Out put t i ng char act er s wi t h put char ( ) */2: #i ncl ude 3:4: mai n( )5: {6: put char ( 65) ;7: put char ( 10) ;8: put char ( 66) ;9: put char ( 10) ;10: put char( 67) ;11: put char ( 10) ;12: r et ur n 0;13: }
Kt qu:AB
C
Hm printf()
#i ncl ude i nt pr i nt f ( const char *f or mat- str i ng, . . . ) ;
VD: printf("The sum of two integers %d + %d is: %d.\n",a,b,c);
Cc c t format dng vi printf():
%c K t%d S nguyn%i S nguyn (nh %d).%f S thc du phy ng%e S thc dng a.aaae+bbb%E S thc dng a.aaaE+bbb%g Dng %f hoc %e, nu ci no ngn hn.%G Dng %f hoc %E, nu ci no ngn hn.%o S octa khng du
%s Chui k t%u S nguyn khng du%x S hexa khng du (vi x thng)%X S hexa khng du (vi X hoa)%p Hin th i s l pointer%% Cho ra k t (%).
-
8/12/2019 Mt s Kin thc c bn v C.pdf
18/153
18
i thnh s Hexa
V d:1: / *Conver t i ng t o hex numbers */2: #i ncl ude 3:4: mai n( )5: {6: pr i nt f ( "Hex(upper case) Hex(l ower case) Deci mal \ n") ;7: pr i nt f ( "%X %x %d\ n", 0, 0, 0) ;8: pr i nt f ( "%X %x %d\ n", 1, 1, 1) ;9: pr i nt f ( "%X %x %d\ n", 2, 2, 2) ;10: pr i nt f ( "%X %x %d\ n", 3, 3, 3) ;11: pr i nt f ( "%X %x %d\ n", 4, 4, 4) ;12: pr i nt f ( "%X %x %d\ n", 5, 5, 5) ;13: pr i nt f ( "%X %x %d\ n", 6, 6, 6) ;14: pr i nt f ( "%X %x %d\ n", 7, 7, 7) ;15: pr i nt f ( "%X %x %d\ n", 8, 8, 8) ;16: pr i nt f ( "%X %x %d\ n", 9, 9, 9) ;
17: pr i nt f ( "%X %x %d\ n" , 10, 10, 10) ;18: pr i nt f ( "%X %x %d\ n" , 11, 11, 11) ;19: pr i nt f ( "%X %x %d\ n" , 12, 12, 12) ;20: pr i nt f ( "%X %x %d\ n" , 13, 13, 13) ;21: pr i nt f ( "%X %x %d\ n" , 14, 14, 14) ;22: pr i nt f ( "%X %x %d\ n" , 15, 15, 15) ;23: r et ur n 0;24: }
Kt qu:Hex(upper case) Hex( l owercase) Deci mal0 0 01 1 12 2 2
3 3 34 4 45 5 56 6 67 7 78 8 89 9 9A a 10B b 11C c 12D d 13E e 14F f 15
Format s nguyn xc nh s ch s: % (-0n) d1: / *Speci f yi ng mi ni mum f i el d wi dt h */2: #i ncl ude 3:4: mai n( )5: {6: i nt num1, num2;7:8: num1 = 12;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
19/153
19
9: num2 = 12345;10: pr i nt f ( "%d\ n", num1) ;11: pr i nt f ( "%d\ n", num2) ;12: pr i nt f ( "%5d\ n", num1) ;13: pr i nt f ( "%05d\ n" , num1) ;14: pr i nt f ( "%2d\ n", num2) ;15: r et ur n 0;16: }Kt qu:
1212345
120001212345
Sp xp s nguyn thng hng bn phi hoc tri1: / *Al i gni ng out put */2: #i ncl ude 3:
4: mai n( )5: {6: i nt num1, num2, num3, num4, num5;7:8: num1 = 1;9: num2 = 12;10: num3 = 123;11: num4 = 1234;12: num5 = 12345;13: pr i nt f ( "%8d %- 8d\ n" , num1, num1) ;14: pr i nt f ( "%8d %- 8d\ n" , num2, num2) ;15: pr i nt f ( "%8d %- 8d\ n" , num3, num3) ;16: pr i nt f ( "%8d %- 8d\ n" , num4, num4) ;17: pr i nt f ( "%8d %- 8d\ n" , num5, num5) ;18: r et ur n 0;19: }
Kt qu:1 1
12 12123 123
1234 123412345 12345
Format biu dim chnh xc: % (a.b) f , % (a.b) d1: / * Usi ng pr eci s i on speci f i er s */2: #i ncl ude
3:4: mai n( )5: {6: i nt i nt _num;7: doubl e f l t _num;8:9: i nt _num = 123;10: f l t _num = 123. 456789;11: pr i nt f ( "Def aul t i nt eger f or mat : %d\ n", i nt _num) ;12: pr i nt f ( "Wi t h pr eci si on speci f i er : %2. 8d\ n", i nt _num) ;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
20/153
20
13: pr i nt f ( "Def aul t f l oat f or mat : %f \ n", f l t _num) ;14: pr i nt f ( "Wi t h pr eci si on speci f i er : %- 10. 2f \ n", f l t _num) ;15: r et ur n 0;16: }
Kt qu:Def aul t i nt eger f ormat: 123
Wi t h pr eci si on speci f i er : 00000123Def aul t f l oat f ormat : 123. 456789Wi t h pr eci si on speci f i er : 123. 46
Bi tp
1. Xut ln mn nh k t B, y v e.2. Hin th ln mn nh 2 s 123 v 123.456 v xp thng hng v phatri.3. Biu din 3 s 15, 150, and 1500 di dng hexa.4. Chng trnh sau c li g?
mai n( )
{ i nt ch;ch = getchar( ) ;put char ( ch) ;r et ur n 0;
}
CHNG II: TON T V LNH IU KHIN
VI. Thao tc d liu vi cc ton t
Ni dung:
Vi phn ny ta tm hiu k hn v cc ton t:
Ton t gn(Arithmetic assignment operators) Tan t tng gim(Increment and decrement operators ) Ton t quan h(Relational operators) Ton t chuyn i kiu(Cast operator)
Tan t gn s hc
Tan t gn (=)
Bin = biu thc;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
21/153
21
Bng ton t (=), gi tr kt qu ca v tri s c gn vo b nh dnh cho bin vphi..
Cnh bong nhm ln (=) with the biu thc quan h (= =).
Mt s cch vit n gin ha trong C
x = x + y x += yx = x - y x -= yx = x * y x *= yx = x / y x /= yx = x % y x %= y
Ch : x = x*y + z khc vi x*=y +z x = x*(y + z)
V d:1: / * Usi ng ar i t hmet i c assi gnment oper at ors */2: #i ncl ude 3:4: mai n( )5: {6: i nt x, y, z;7:8: x = 1; / * i ni t i al i ze x * /9: y = 3; / * i ni t i al i ze y * /10: z = 10; / * i ni t i al i ze z * /11: pr i nt f ( "Gi ven x = %d, y = %d, and z = %d, \ n" , x, y, z) ;12:13: x = x + y;14: pr i nt f ( "x = x + y assi gns %d t o x; \ n" , x) ;15:16: x = 1; / * r eset x */17: x += y;18: pr i nt f ( "x += y assi gns %d t o x; \ n", x) ;19:20: x = 1; / * r eset x */21: z = z * x + y;22: pr i nt f ( "z = z * x + y assi gns %d t o z; \ n", z) ;23:24: z = 10; / * r eset z */25: z = z * ( x + y) ;
26: pr i nt f ( "z = z * ( x + y) assi gns %d t o z; \ n", z) ;27:28: z = 10; / * r eset z */29: z *= x + y;30: pr i nt f ( "z *= x + y assi gns %d t o z. \ n", z) ;31:32: r et ur n 0;33: }
p s:
-
8/12/2019 Mt s Kin thc c bn v C.pdf
22/153
22
Gi ven x = 1, y = 3, and z = 10,x = x + y assi gns 4 t o x;x += y assi gns 4 t o x;z = z * x + y assi gns 13 t o z;z = z * ( x + y) assi gns 40 t o z;
z *= x + y assi gns 40 t o z.
Ton t tng gim
Ton t tng: ++ (cng thm 1) x = x+1 ++xTon t gim: -- (tr i 1) x = x-1 --x
Phn bit: y = x++ ngha l sau khi x cng thm 1 (x=x+1), mi gn cho y (y=x+1)y = ++x ngha l y ly gi tr ca x ban u (y=x), sau x mi cng
thm 1 (x=x+1)
V d:1: / * pr e- or post- i ncrement ( decr ement ) oper at or s */2: #i ncl ude 3:4: mai n( )5: {6: i nt w, x, y, z , resul t ;7:8: w = x = y = z = 1; / * i ni t i al i ze x and y */9: pr i nt f ( "Gi ven w = %d, x = %d, y = %d, and z = %d, \ n", w, x, y,z ) ;10:11: r esul t = ++w;
12: pr i nt f ( "++w gi ves: %d\ n", r esul t ) ;13: r esul t = x++;14: pr i nt f ( "x++ gi ves: %d\ n", r esul t ) ;15: r esul t = - - y;16: pr i nt f ( " - - y gi ves: %d\ n", resul t ) ;17: r esul t = z- - ;18: pr i nt f ( "z- - gi ves: %d\ n", resul t ) ;19: r et ur n 0;20: }
Kt qu:
Gi ven w = 1, x = 1, y = 1, and z = 1,++w gi ves: 2x++ gi ves: 1- - y gi ves: 0z- - gi ves: 1
Tan t quan h
Kt qu cc biu thc c ton t quan h thu c theo nguyn tc i s Boole.
-
8/12/2019 Mt s Kin thc c bn v C.pdf
23/153
23
Ton t M t Ton t M t
= = Bng < Nh hn!= Khng bng >= Ln hn hoc bng> Ln hn = y) ;14: pr i nt f ( "x == y pr oduces: %d\ n" , x == y) ;15: pr i nt f ( "x < z pr oduces: %d\ n", x < z) ;16: pr i nt f ( "y > z pr oduces: %d\ n", y > z) ;17: pr i nt f ( "x ! = y - 18 pr oduces: %d\ n", x ! = y - 18) ;18: pr i nt f ( "x + y ! = z pr oduces: %d\ n" , x + y ! = z) ;19: r et ur n 0;20: }
p s:Gi ven x = 7, y = 25, and z = 24. 46,x >= y produces: 0x == y produces: 0x < z produces: 1y > z produces: 1x ! = y - 18 produces: 0x + y ! = z produces: 1
Tan t chuyn i kiu
(data-type) x
V d: (float)5 c tc dng chuyn integer 5 thnh s float 5.0.
V d:1: / * Usi ng t he cast oper at or */2: #i ncl ude 3:4: mai n( )5: {6: i nt x, y;7:8: x = 7;9: y = 5;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
24/153
24
10: pr i nt f ( "Gi ven x = %d, y = %d\ n" , x, y) ;11: pr i nt f ( "x / y pr oduces: %d\ n", x / y) ;12: pr i nt f ( "( f l oat ) x / y produces: %f \ n", ( f l oat ) x / y) ;13: r et ur n 0;14: }
Kt qu:
Gi ven x = 7, y = 5x / y pr oduces: 1( f l oat ) x / y pr oduces: 1. 400000
Bi tp
1. Vi x = 3 v y = 6, z = x * y = = 18 bng bao nhiu?3. Phn bit:pri nt f ( "x++ pr oduces: %d\ n" , x++) ;pr i nt f ( "Now x cont ai ns: %d\ n", x);
pr i nt f ( "x = x++ produces: %d\ n", x = x++) ;pr i nt f ( "Now x cont ai ns: %d\ n", x) ;
4. Trong chng trnh di y, c ci g sai ?#i ncl ude mai n( ){
i nt x, y;
x = y = 0;
pr i nt f ( "The compar i son r esul t i s: %d\ n", x = y);r et ur n 0;}
VII. Cc lnh biu th s lp li
Ni dung:
Vi phn ny ta lm quen vi cc lnh biu th cc vng lp s lp li ca mt cmlnh no vi mt thng s no thay i c quy lut.
Lnh for Lnh while Lnh do - while
-
8/12/2019 Mt s Kin thc c bn v C.pdf
25/153
25
Lnh For
f or ( expr essi on1; expr essi on2; expr essi on3) {st atement 1;st atement 2;.
.
.}
Trnh t:1) Tnh gi tr expression1; 2) Tnh gi tr expression2; 3) Nu gitr expression2 sai, nhy khi lnh For; nu ng, thc hinstatement1,2; 4) Tnh gi tr expression3 v quay li bc 2).
V du:1: / * 07L01. c: Conver t i ng 0 t hr ough 15 t o hex numbers */2: #i ncl ude
3:4: mai n( )5: {6: i nt i ;7:8: pr i nt f ( "Hex(upper case) Hex(l ower case) Deci mal \ n" ) ;9: f or ( i =0; i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
26/153
26
f or ( i =0; i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
27/153
27
11: put char ( c) ;12: }13: pr i nt f ( "\ nOut of t he f or l oop. Bye! \ n") ;14: r et ur n 0;15: }
Kt qu:Ent er a charact er :( ent er x t o exi t )HHiixxOut of t he f or l oop. Bye!
Lnh While
whi l e ( expr essi on) {st atement 1;st atement 2;...
}
Trnh t:1) Tnh gi tr expression; 2) Nu gi tr expression sai, nhy khilnh while; nu ng, thc hin statement1,2v quay li bc 1).
V d:1: / * Usi ng a whi l e l oop */2: #i ncl ude 3:4: mai n( )5: {6: i nt c;7:8: c = ` `;9: pr i nt f ( "Ent er a char acter : \ n( ent er x t o exi t ) \ n") ;10: whi l e ( c ! = `x' ) {11: c = get c( st di n) ;12: put char ( c) ;
13: }14: pr i nt f ( "\ nOut of t he whi l e l oop. Bye! \ n") ;15: r et ur n 0;16: }
Kt qu:Ent er a charact er :
( ent er x t o exi t )HH
-
8/12/2019 Mt s Kin thc c bn v C.pdf
28/153
28
iixxOut of t he whi l e l oop. Bye!
Vng lp While v hnwhi l e ( 1) {st atement 1;st atement 2;...
}
Nht thit phi c iu kin nhy ra khi vng lp. Nu khng my s ng yn v chc th khi ng cng tr li.
Vng lp do-whiledo {
st atement 1;st atement 2;...
} whi l e (expr essi on) ;
Trnh t: 1) Thc hin statement1,2; 2) Nu gi tr expression sai, nhykhi vng lp; nu ng, quay li bc 1).
V d:1: / * Usi ng a do- whi l e l oop */2: #i ncl ude 3:4: mai n( )5: {6: i nt i ;7:8: i = 65;9: do {10: pr i nt f ( "The numer i c val ue of %c i s %d. \ n", i , i ) ;11: i ++;
12: } whi l e ( i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
29/153
29
The numer i c val ue of G i s 71.
Vng lp lng nhau
V d:
1: / * Demonst r at i ng nest ed l oops */2: #i ncl ude 3:4: mai n( )5: {6: i nt i , j ;7:8: f or ( i =1; i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
30/153
30
2. Cho mt s nguyn dng long. Vit chng trnh xut ln mn nh, trong s c nhng ch s no bng 4?
VIII. Mt s ton t c bitNi dung:
Vi phn ny ta lm quen vi cc ton t c bit sau:
Tan t sizeof Tan t logic Tan t thao tc bit Tan t iu kin
Tan t sizeof
si zeof ( expr essi on)
Kt qu l s byte phn b nh cha gi tr ca expression.
V d:1: / * Usi ng t he si zeof oper at or */2: #i ncl ude
3:4: mai n( )5: {6: char ch = ` `;7: i nt i nt _num = 0;8: f l oat f l t _num = 0. 0f ;9: doubl e dbl _num = 0. 0;10:11: pr i nt f ( "The si ze of char i s: %d- byt e\ n", si zeof ( char ) ) ;12: pr i nt f ( "The si ze of ch i s: %d- byt e\ n", si zeof ch ) ;13: pr i nt f ( "The s i ze of i nt i s : %d- byt e\ n", s i zeof ( i nt ) ) ;14: pr i nt f ( "The si ze of i nt _num i s: %d- byt e\ n", si zeofi nt _num) ;
15: pr i nt f ( "The si ze of f l oat i s: %d- byt e\ n",si zeof ( f l oat ) ) ;
16: pr i nt f ( "The si ze of f l t _num i s: %d- byt e\ n", s i zeoff l t _num) ;17: pr i nt f ( "The si ze of doubl e i s: %d- byt e\ n", si zeof ( doubl e) ) ;18: pr i nt f ( "The si ze of dbl _num i s: %d- byte\ n", si zeof dbl _num) ;19: r et ur n 0;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
31/153
31
20: }
Kt qu:
C: \ app> 08L01The si ze of char i s: 1- byt eThe si ze of ch i s: 1- byt e
The si ze of i nt i s: 2- byt eThe si ze of i nt _num i s: 2- byt eThe si ze of f l oat i s: 4- byt eThe si ze of f l t _num i s: 4- byt eThe si ze of doubl e i s: 8- byt eThe si ze of dbl _num i s: 8- byt eC: \ app>
Ton t Logic
&& Tan t logic AND|| Tan t logic OR
! Tan t logic ph nh
Ghi ch
Khi biu thc tr gi tr khc 0, biu thc logic tr gi tr TRUE.Khi biu thc tr gi tr bng 0, biu thc logic tr gi tr FALSE.
Exp1 Exp2 Exp1 && Exp2 Exp1 || Exp2 !Exp11 1 1 1 01 0 0 1 00 1 0 1 10 0 0 0 1
V d:1: / * Usi ng t he l ogi cal AND oper ator */2: #i ncl ude 3:
4: mai n( )5: {6: i nt num;7:8: num = 0;9: pr i nt f ( "The AND oper at or r et ur ns: %d\ n" ,10: ( num%2 == 0) && ( num%3 == 0) ) ;11: num = 2;12: pr i nt f ( "The AND oper at or r et ur ns: %d\ n" ,13: ( num%2 == 0) && ( num%3 == 0) ) ;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
32/153
32
14: num = 3;15: pr i nt f ( "The AND oper at or r et ur ns: %d\ n" ,16: ( num%2 == 0) && ( num%3 == 0) ) ;17: num = 6;18: pr i nt f ( "The AND oper at or r et ur ns: %d\ n" ,19: ( num%2 == 0) && ( num%3 == 0) ) ;20:21: r et ur n 0;22: }
Kt qu:
The AND operat or r et urns: 1The AND operat or r et urns: 0The AND operat or r et urns: 0The AND operat or r et urns: 1
V d:1: / * Usi ng t he l ogi cal OR oper at or */2: #i ncl ude
3:4: mai n( )5: {6: i nt num;7:8: pr i nt f ( "Ent er a si ngl e di gi t t hat can be di vi ded\ nby bot h 2 and3 : \n " ) ;9: f or ( num = 1; ( num%2 ! = 0) | | ( num%3 ! = 0) ; )10: num = get char( ) - 48;11: pr i nt f ( "You got such a number : %d\ n" , num) ;12: r et ur n 0;13: }
Kt qu:
Ent er a si ngl e di gi t t hat can be di vi dedby bot h 2 and 3:23456
You got such a number: 6
V d:1: / * Usi ng t he l ogi cal negat i on oper at or */2: #i ncl ude
3:4: mai n( )5: {6: i nt num;7:8: num = 7;9: pr i nt f ( "Gi ven num = 7\ n") ;10: pr i nt f ( "! ( num < 7) r et ur ns: %d\ n", ! ( num < 7) ) ;11: pr i nt f ( "! ( num > 7) r et ur ns: %d\ n", ! ( num > 7) ) ;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
33/153
33
12: pr i nt f ( "! ( num == 7) r et ur ns: %d\ n", ! ( num == 7) ) ;13: r et ur n 0;14: }
Kt qu:
Gi ven num = 7
! ( num < 7) r et ur ns: 1! ( num > 7) r et ur ns: 1! ( num == 7) r et ur ns: 0
Thao tc Bits
Ton
tM t Ton t M t
& Php hi bit AND ~ Php ly phn b| Php tuyn bit OR >> Php dch tri 1 bit^ Php tuyn loi tr XOR
-
8/12/2019 Mt s Kin thc c bn v C.pdf
34/153
34
Gi ven x = 4321, i . e. , 0X10E1y = 5678, i . e. , 0X162E
x & y r et ur ns: 4128, i . e. , 0X1020x | y r et ur ns: 5871, i . e. , 0X16EF
x ^ y r et ur ns: 1743, i . e. , 0X06CF~x r et ur ns: 61214, i . e. , 0XEF1E
Cnh bong lm ln gia ton tquan h && and || v ton t logic & and | . V d:( x=1) & ( y=10)( x=1) && ( y=10)
Ton t dch chuyn bitx >> yx > 2 - > ( 1 * 23 + 0 *22 + 0 * 21 + 0 *20) >> 2
s l:
(0 * 23 + 0 * 22 + 1 *21 + 0 * 20) - > 0010 ( bi nary) - > 2 ( deci mal ) .
V d:1: / * Usi ng shi f t oper at or s */2: #i ncl ude
3:4: mai n( )5: {6: i nt x, y, z ;7:8: x = 255;9: y = 5;10: pr i nt f ( "Gi ven x = %4d, i . e. , 0X%04X\ n" , x, x) ;11: pr i nt f ( " y = %4d, i . e. , 0X%04X\ n", y, y) ;12: z = x >> y;13: pr i nt f ( "x >> y r et ur ns: %6d, i . e. , 0X%04X\ n", z, z);14: z = x > y ret ur ns: 7, i . e. , 0X0007x
-
8/12/2019 Mt s Kin thc c bn v C.pdf
35/153
35
x >> y x / 2yx y?x:y s cho ta gi tr ln nht gia x v y.
V d:1: / * Usi ng t he ?: oper at or */2: #i ncl ude 3:4: mai n( )5: {
6: i nt x;7:8: x = si zeof ( i nt ) ;9: pr i nt f ( "%s\ n",10: ( x == 2) ? "The i nt dat a t ype has 2 bytes. " : "i nt doesn' thave 2
byt es. ") ;11: pr i nt f ( "The maxi mum val ue of i nt i s: %d\ n",12: ( x ! = 2) ? ~( 1
-
8/12/2019 Mt s Kin thc c bn v C.pdf
36/153
36
signed unsigned short long
Cc hm ton hc c bn: Hm sin(), cos(), tan() Hm pow(), sqrt()
T kha chuyn i signedsi gned char ch;
Bin char cng ha c du,ngha l khong gi tr ca n s l -128 n 127. Bin char
khng du c khong t 0 255.
Ghi ch
chuyn mt s dng thnh 1 s m dng nh phn, ta ly phn b ca s dngdng nh phn ri cng thm 1.V d: Biu din dng nh phn ca -12345 ?123450011000000111001.
~ 0011000000111001 11001111110001101100111111000110 + 11100111111000111 l dng nh phn ca -12345.
T kha chuyn i unsignedunsi gned i nt x;
s nguyn 16 bits mc nh c khong [-32768, 32767] bin i thnh s nguyn x ckhong gi tr [0, 65535] (216_1).
Chun ANSI cho php ch th hng s thnh khng du bng tip v ng U hoc u.V d:
unsi gned i nt x, y;x = 12345U;y = 0xABCDu;
V d:1: / * Usi ng si gned and unsi gned modi f i er s */2: #i ncl ude 3:4: mai n( )5: {6: si gned char ch;7: i nt x;8: unsi gned i nt y;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
37/153
37
9:10: ch = 0xFF;11: x = 0xFFFF;12: y = 0xFFFFu;13: pr i nt f ( "The deci mal of si gned 0xFF i s %d. \ n", ch) ;14: pr i nt f ( "The deci mal of si gned 0xFFFF i s %d. \ n", x) ;15: pr i nt f ( "The deci mal of unsi gned 0xFFFFu i s %u. \ n", y) ;16: pr i nt f ( "The hex of deci mal 12345 i s 0x%X. \ n" , 12345) ;17: pr i nt f ( "The hex of deci mal - 12345 i s 0x%X. \ n" , - 12345) ;18: r et ur n 0;19: }
Kt qu:
The deci mal of si gned 0xFF i s - 1The deci mal of si gned 0xFFFF i s - 1.The deci mal of unsi gned 0xFFFFu i s 65535.The hex of deci mal 12345 i s 0x3039.The hex of deci mal - 12345 i s 0xCFC7.
T kho thay i kch thc d liu
T kha shortshor t x;unsi gned shor t y;
T kha Longl ong i nt x;
Chun ANSI cho php ch th hng s thnh long bng tip v ng L hoc l.V d:
l ong i nt x, y;x = 123456789l ;y = 0xABCD1234L;
V d:1: / * Usi ng shor t and l ong modi f i er s */2: #i ncl ude 3:4: mai n( )5: {6: pr i nt f ( "The si ze of shor t i nt i s: %d. \ n",7: s i zeof (short i nt ) ) ;
8: pr i nt f ( "The si ze of l ong i nt i s: %d. \ n",9: s i zeof ( l ong i nt ) ) ;10: pr i nt f ( "The si ze of f l oat i s: %d. \ n",11: s i zeof ( f l oat ) ) ;12: pr i nt f ( "The si ze of doubl e i s: %d. \ n",13: si zeof ( doubl e) ) ;14: pr i nt f ( "The si ze of l ong doubl e i s: %d. \ n",15: si zeof ( l ong doubl e) ) ;16: r et ur n 0;17: }
-
8/12/2019 Mt s Kin thc c bn v C.pdf
38/153
38
Kt qu:
The si ze of shor t i nt i s: 2.The si ze of l ong i nt i s: 4.The si ze of f l oat i s: 4.The si ze of doubl e i s: 8.
The si ze of l ong doubl e i s: 10.
Thm h, l, or L to cc c t Format : %hd, %hi, hoc %hu
V d:. S dng %hd, %ld, and %lu.1: / * Usi ng %hd, %l d, and %l u speci f i er s */2: #i ncl ude 3:4: mai n( )5: {6: shor t i nt x;7: unsi gned i nt y;
8: l ong i nt s;9: unsi gned l ong i nt t ;10:11: x = 0xFFFF;12: y = 0xFFFFU;13: s = 0xFFFFFFFFl ;14: t = 0xFFFFFFFFL;15: pr i nt f ( "The shor t i nt of 0xFFFF i s %hd. \ n", x);16: pr i nt f ( "The unsi gned i nt of 0xFFFF i s %u. \ n", y) ;17: pr i nt f ( "The l ong i nt of 0xFFFFFFFF i s %l d. \ n", s) ;18: pr i nt f ( "The unsi gned l ong i nt of 0xFFFFFFFF i s %l u. \ n", t ) ;19: r et ur n 0;20: }
Kt qu:
The shor t i nt of 0xFFFF i s - 1.The unsi gned i nt of 0xFFFF i s 65535.The l ong i nt of 0xFFFFFFFF i s - 1.The unsi gned l ong i nt of 0xFFFFFFFF i s 4294967295
Hm ton hc trong C
Mt cch c bn c th chia lm 3 nhm:
Hm lnggic nh acos(), cos(), v cosh(). Hm m v log nh exp(), pow(), and log10(). Cc hm khc nh ceil(), fabs(), and floor().
Khi dng chng phi gi #include math.h l header c bit dnh cho cc hm ton hc. y chng ta ch gii thiu vi hm cn bn.
-
8/12/2019 Mt s Kin thc c bn v C.pdf
39/153
39
sin(), cos(), v tan()#i ncl ude doubl e si n( doubl e x) ;
#i ncl ude doubl e cos( doubl e x) ;
#i ncl ude doubl e t an( doubl e x) ;
Bin x c n v l rad v kiu double.
V d:1: / * Usi ng si n( ) , cos() , and t an( ) f uncti ons */2: #i ncl ude 3: #i ncl ude 4:5: mai n( )
6: {7: doubl e x;8:9: x = 45. 0; / * 45 degr ee */10: x *= 3. 141593 / 180. 0; / * conver t t o r adi ans */11: pr i nt f ( "The si ne of 45 i s: %f . \ n", s i n( x) ) ;12: pr i nt f ( "The cosi ne of 45 i s: %f . \ n", cos(x)) ;13: pr i nt f ( "The t angent of 45 i s: %f . \ n", tan( x) ) ;14: r et ur n 0;15: }
Kt qu:
The si ne of 45 i s: 0. 707107.The cosi ne of 45 i s: 0. 707107.The t angent of 45 i s: 1. 000000.
pow() v sqrt()#i ncl ude doubl e pow( doubl e x, doubl e y) ;
#i ncl ude doubl e sqr t ( doubl e x);
Trong c 2 hm trn bin x l s khng m.
V d:1: / * Usi ng pow( ) and sqr t ( ) f unct i ons */2: #i ncl ude 3: #i ncl ude 4:5: mai n( )6: {7: doubl e x, y, z;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
40/153
40
8:9: x = 64. 0;10: y = 3. 0;11: z = 0. 5;12: pr i nt f ( "pow( 64. 0, 3. 0) r et ur ns: %7. 0f \ n", pow( x, y) ) ;13: pr i nt f ( "sqr t ( 64. 0) r et ur ns: %2. 0f \ n", sqr t ( x) ) ;14: pr i nt f ( "pow( 64. 0, 0. 5) r et ur ns: %2. 0f \ n", pow( x, z) ) ;15: r et ur n 0;16: }
Kt qu:
pow( 64. 0, 3. 0) r et ur ns: 262144sqr t ( 64. 0) r et ur ns: 8pow( 64. 0, 0. 5) r et ur ns: 8
Bi tp:
1. Cho an lnh sau:i nt x;unsi gned i nt y;x = 0xAB78;y = 0xAB78;
Hy vit chng trnh biu din cc gi tr x v y bng s thp phn ln mn nh.
2. Lp chng trnh tnh cc biu thc sau:
X. Cc lnh iu khin tc v chng trnh
Ni dung:
Vi phnny ta lm quen vi cc cu lnh iu kin sau:
if if-else switch break
-
8/12/2019 Mt s Kin thc c bn v C.pdf
41/153
41
continue goto
Lnh if
i f ( expr essi on) {st atement 1;st atement 2;...
}
Nu expression l ng (TRUE), cc statement1,2 s c thi hnh; nusai, chng trnh b qua.
V d:1: / * Usi ng t he i f st at ement */2: #i ncl ude 3:4: mai n( )5: {6: i nt i ;7:8: pr i nt f ( " I nt eger s t hat can be di vi ded by both 2 and 3\ n") ;9: pr i nt f ( "( wi t hi n t he r ange of 0 t o 100) : \ n") ;10: f or ( i =0; i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
42/153
42
9096
Lnh if-else
i f ( expr essi on) {
st atement 1;st atement 2;...
}el se {
st atement _A;st atement _B;...
}
Nu expression l ng (TRUE), cc statement1,2 s c thi hnh; nusai, ), cc statement_A,_B s c thi hnh.
V d:1: / * Usi ng t he i f - el se st at ement */2: #i ncl ude 3:4: mai n( )5: {6: i nt i ;7:
8: pr i nt f ( "Even Number Odd Number \ n") ;9: f or ( i =0; i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
43/153
43
V d:1: / * Usi ng nest ed i f st atement s */2: #i ncl ude 3:4: mai n( )5: {
6: i nt i ;7:8: f or ( i =- 5; i 0)10: i f ( i %2 == 0)11: pr i nt f ( "%d i s an even number . \ n", i ) ;12: el se13: pr i nt f ( "%d i s an odd number . \ n", i ) ;14: el se i f ( i == 0)15: pr i nt f ( "The number i s zer o. \ n") ;16: el se17: pr i nt f ( "Negat i ve number : %d\ n", i ) ;18: }
19: r et ur n 0;20: }
Kt qu:Negat i ve number : - 5Negat i ve number : - 4Negat i ve number : - 3Negat i ve number : - 2Negat i ve number : - 1
The number i s zero.1 i s an odd number .2 i s an even number .3 i s an odd number .4 i s an even number .5 i s an odd number .
Lnh switch
Lnh iu kinvi nhiu kh nng xy ra.
swi t ch ( expr essi on) {case expr essi on1:
st at ement 1;case expr essi on2:
st at ement 2;..
.def aul t :st at ement - def aul t ;
}
V d:1: / * Usi ng t he swi t ch st at ement * /2: #i ncl ude 3:
-
8/12/2019 Mt s Kin thc c bn v C.pdf
44/153
44
4: mai n( )5: {6: i nt day;7:8: pr i nt f ( "Pl ease ent er a s i ngl e di gi t f or a day\ n") ;9: pr i nt f ( "( wi t hi n t he r ange of 1 t o 3) : \ n") ;10: day = getchar( ) ;11: swi t ch ( day) {12: case `1' :13: pr i nt f ( "Day 1\ n") ;14: case `2' :15: pr i nt f ( "Day 2\ n") ;16: case `3' :17: pr i nt f ( "Day 3\ n") ;18: def aul t :19: ;20: }21: r et ur n 0;22: }
Kt qu:Pl ease ent er a si ngl e di gi t f or a day( wi t hi n t he r ange of 1 t o 3) :3Day 3
Nu cho gi tr l 1, kt qu s l:
Pl ease ent er a si ngl e di gi t f or a day( wi t hi n t he r ange of 1 t o 3) :1Day 1
Day 2Day 3
Ta thy sau khi thi hnh 1 trng hp, cc trng hp sau cng tun t thi hnh.Mun khng xy ra, phi dng lnh break nhy ra khi lnh iu kin.
Lnh break
Dng chm dt thi hnh cm lnh no trong lnh iu kin switch hoc vng lpfor, while.
V d:1: / * Addi ng t he br eak st atement * /2: #i ncl ude 3:4: mai n( )5: {6: i nt day;7:8: pr i nt f ( "Pl ease ent er a s i ngl e di gi t f or a day\ n") ;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
45/153
45
9: pr i nt f ( "( wi t hi n t he r ange of 1 t o 7) : \ n") ;10: day = getchar( ) ;11: swi t ch ( day) {12: case `1' :13: pr i nt f ( "Day 1 i s Sunday. \ n") ;14: br eak;15: case `2' :16: pr i nt f ( "Day 2 i s Monday. \ n") ;17: br eak;18: case `3' :19: pr i nt f ( "Day 3 i s Tuesday. \ n") ;20: br eak;21: case `4' :22: pr i nt f ( "Day 4 i s Wednesday. \ n") ;23: br eak;24: case `5' :25: pr i nt f ( "Day 5 i s Thur sday. \ n") ;26: br eak;27: case `6' :28: pr i nt f ( "Day 6 i s Fr i day. \ n") ;
29: br eak;30: case `7' :31: pr i nt f ( "Day 7 i s Sat ur day. \ n") ;32: br eak;33: def aul t :34: pr i nt f ( "The di gi t i s not wi t hi n t he r ange of 1 t o 7. \ n") ;35: br eak;36: }37: r et ur n 0;38: }
Kt qu:
Pl ease ent er a si ngl e di gi t f or a day
( wi t hi n t he r ange of 1 t o 7) :1Day 1 i s Sunday.
V d:
1: / * Br eaki ng an i nf i ni t e l oop */2: #i ncl ude 3:4: mai n( )5: {6: i nt c;
7:8: pr i nt f ( "Ent er a char acter : \ n( ent er x t o exi t ) \ n") ;9: whi l e ( 1) {10: c = get c( st di n) ;11: i f ( c == x' )12: br eak;13: }14: pr i nt f ( "Br eak t he i nf i ni t e whi l e l oop. Bye!\ n") ;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
46/153
46
15: r et ur n 0;16: }
Kt qu:
Ent er a charact er :( ent er x t o exi t )
HIxBr eak the i nf i ni t e whi l e l oop. Bye!
Lnh continue
Thay v chm dt mt vng lp gia chng, c khi ta cn tip tc vng lp m nhy quamt s cu lnh no . Trong trng hp ny ta dng lnh continue. Gp lnh ny,chng trnh nhy ngay tr li v u lnh lp v tip tc.
V d:1: / * Usi ng t he cont i nue st atement */2: #i ncl ude 3:4: mai n( )5: {6: i nt i , sum;7:8: sum = 0;9: f or ( i =1; i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
47/153
47
cc lnh trn thng hay gy ra nhng li nghim trng khng d tnh trc c mta kh dng phng tin d sa li (debugger) tm ra.
Bi tp
1. Cho x = 4, y = 2, v operator = `-', Kt qu ca cc cm lnh sau l g?swi t ch ( oper at or ) {
case `+' : x += y;case `- ' : x - = y;case `*' : x *= y;case `/ ' : x / = y;def aul t : br eak;
}
swi t ch ( oper at or ) {case `+' : x += y; br eak;case `- ' : x - = y; break;
case `*' : x *= y; br eak;case `/ ' : x / = y; br eak;def aul t : br eak;
}
2. Gi tr ca x sau cm lnh ny?x = 1;f or ( i =2; i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
48/153
48
Tan t address-of (&) Tan t dereference (*)
Bin con tr
Con tr l mt bin dng ch vo v tr mt bin khc th hin qua a ch ca bin trong b nh. Cho nn con tr cn gi l bin a ch.
Tan tAddress-of (&)
Tan t & p t ln mt bin no s cho ta bit a ch ca bin trong b nh.
l ong i nt x, y;y = &x;
V d:
1: / * Obt ai ni ng addr esses */2: #i ncl ude 3:4: mai n( )5: {6: char c;7: i nt x;8: f l oat y;9:10: pr i nt f ( " c: addr ess=0x%p, cont ent =%c\ n" , &c, c) ;
11: pr i nt f ( "x: addr ess=0x%p, cont ent =%d\ n" , &x, x) ;12: pr i nt f ( "y: addr ess=0x%p, cont ent =%5. 2f \ n" , &y, y) ;13: c = `A' ;14: x = 7;15: y = 123. 45;16: pr i nt f ( " c: addr ess=0x%p, cont ent =%c\ n" , &c, c) ;17: pr i nt f ( "x: addr ess=0x%p, cont ent =%d\ n" , &x, x) ;18: pr i nt f ( "y: addr ess=0x%p, cont ent =%5. 2f \ n" , &y, y) ;19: r et ur n 0;20: }
Kt qu:
c: address=0x1AF4, cont ent =@x: address=0x1AF2, cont ent =- 32557y: address=0x1AF6, cont ent =0. 00c: address=0x1AF4, cont ent =Ax: address=0x1AF2, cont ent =7y: address=0x1AF6, cont ent =123. 45
Ghi ch
c t format %p dng trong printf() c h tr theo ANSI. Tuy nhin nu b bin dch
-
8/12/2019 Mt s Kin thc c bn v C.pdf
49/153
49
khng cho php, c th dng %u hoc %lu.
Khai bo con tr
data- t ype *poi nt er - name;
V d:
char *pt r _c; / * decl ar e a poi nt er t o a char act er */
i nt *pt r _i nt ; / * decl ar e a poi nt er t o an i nt eger */
f l oat *pt r_f l t ; / * decl ar e a poi nt er t o a f l oat i ng- poi nt * /
V d:
1: / * Decl ar i ng and assi gni ng val ues t o poi nt er s */2: #i ncl ude 3:4: mai n( )5: {6: char c, *pt r _c;7: i nt x , *pt r_x;8: f l oat y, *pt r_y;9:10: c = `A' ;11: x = 7;12: y = 123. 45;13: pr i nt f ( " c: addr ess=0x%p, cont ent =%c\ n" , &c, c) ;14: pr i nt f ( "x: addr ess=0x%p, cont ent =%d\ n" , &x, x) ;
15: pr i nt f ( "y: addr ess=0x%p, cont ent =%5. 2f \ n" , &y, y) ;16: pt r _c = &c;17: pr i nt f ( "pt r _c: addr ess=0x%p, cont ent =0x%p\ n", &pt r _c, pt r _c) ;18: pr i nt f ( "*pt r _c => %c\ n", *pt r _c);19: pt r _x = &x;20: pr i nt f ( "pt r _x: addr ess=0x%p, cont ent =0x%p\ n", &pt r _x, pt r _x) ;21: pr i nt f ( "* pt r _x => %d\ n", *pt r _x);22: pt r _y = &y;23: pr i nt f ( "pt r _y: addr ess=0x%p, cont ent =0x%p\ n", &pt r _y, pt r _y) ;24: pr i nt f ( "*pt r _y => %5. 2f \ n", *pt r _y) ;25: r et ur n 0;26: }
Kt qu:c: address=0x1B38, cont ent =Ax: address=0x1B36, cont ent =7y: address=0x1B32, cont ent =123. 45pt r _c: address=0x1B30, cont ent =0x1B38*pt r _c => Apt r _x: address=0x1B2E, cont ent =0x1B36*pt r _x => 7
-
8/12/2019 Mt s Kin thc c bn v C.pdf
50/153
50
pt r _y: address=0x1B2C, cont ent =0x1B32*pt r _y => 123. 45
Tan t dereference (*)
Tan t n bin * p t ln mt bin con tr s cho ta ni dung hoc gi tr ca bin mbin con tr ch n.
Vi d:char c, *pt r _c;char x;f l oat y, *pt r _y;c = `A' ;pt r _c = &c;x = *pt r _c;
Ta thy, bin x s c gi tr nh c, tc l x=A.
Con tr trng (Null Pointer)
Con tr trng l con tr c gi tr bng 0, n khng ch n mt bin d liu c th noc.
V d:
char *pt r _c;i nt *pt r _ i nt ;
pt r _c = pt r _i nt = 0;
Thay i gi tr bin thng qua con tr
V d:
1: / * Changi ng val ues vi a poi nt er s */2: #i ncl ude 3:4: mai n( )5: {6: char c, *pt r _c;7:8: c = `A' ;
9: pr i nt f ( " c: addr ess=0x%p, cont ent =%c\ n" , &c, c) ;10: pt r _c = &c;11: pr i nt f ( "pt r _c: addr ess=0x%p, cont ent =0x%p\ n", &pt r _c, pt r _c) ;12: pr i nt f ( "*pt r _c => %c\ n", *pt r _c);13: *pt r _c = `B' ;14: pr i nt f ( "pt r _c: addr ess=0x%p, cont ent =0x%p\ n", &pt r _c, pt r _c) ;15: pr i nt f ( "*pt r _c => %c\ n", *pt r _c);16: pr i nt f ( " c: addr ess=0x%p, cont ent =%c\ n" , &c, c) ;17: r et ur n 0;18: }
-
8/12/2019 Mt s Kin thc c bn v C.pdf
51/153
51
Kt qu:
c: address=0x1828, cont ent =Aptr _c: address=0x1826, cont ent =0x1828*pt r _c => Aptr _c: address=0x1826, cont ent =0x1828
*pt r _c => Bc: address=0x1828, cont ent =B
Mt bin c th c nhiu bin con tr khc nhau cng ch n n
V d:
1: / * Poi nt i ng t o t he same t hi ng */2: #i ncl ude 3:4: mai n( )5: {6: i nt x;7: i nt *pt r _1, *pt r_2, *pt r_3;8:9: x = 1234;10: pr i nt f ( "x: addr ess=0x%p, cont ent =%d\ n" , &x, x) ;11: pt r _1 = &x;12: pr i nt f ( "pt r _1: addr ess=0x%p, cont ent =0x%p\ n" , &pt r _1, pt r _1) ;13: pr i nt f ( "* pt r _1 => %d\ n", *pt r _1) ;14: pt r _2 = &x;15: pr i nt f ( "pt r _2: addr ess=0x%p, cont ent =0x%p\ n" , &pt r _2, pt r _2) ;16: pr i nt f ( "* pt r _2 => %d\ n", *pt r _2) ;17: pt r _3 = pt r _1;18: pr i nt f ( "pt r _3: addr ess=0x%p, cont ent =0x%p\ n" , &pt r _3, pt r _3) ;19: pr i nt f ( "* pt r _3 => %d\ n", *pt r _3) ;
20: r et ur n 0;21: }
Kt qu:
x: address=0x1838, cont ent =1234pt r _1: address=0x1834, cont ent =0x1838*pt r _1 => 1234pt r _2: address=0x1836, cont ent =0x1838*pt r _2 => 1234pt r _3: address=0x1832, cont ent =0x1838*pt r _3 => 1234
Bi tp
1. Cho 3 bin integer , x = 512, y = 1024, v z = 2048. Vit chng trnh hin th ach vni dung ca 3 bin trn.
2. Vit chng trnh thay i gi tr ca flt_num ban u l 123.45 thnh 543.21dng bin con tr.
-
8/12/2019 Mt s Kin thc c bn v C.pdf
52/153
52
3. Cho bin k t ch = A. Vit chng trnh thay i gi tr ca cng ha thnh sth t 66 bng bin con tr.
4. Cho 2 bin x=5 v y=6. Vit chng trnh tnh x*y v lu tr gi tr trong x, tt cdng pointer.
XII. C s v mng (arrays)Ni dung:
Vi phn ny ta lm quen vi cc khi nim v mng sau:
Mng mt chiu Lit k mng Mng v con tr Chui k t Mng a chiu Mng c kch thc khng nh trc
Mng mt chiu
Mng l mt tp hp cc bin c cng chung kiu d liu. Khai bo nh sau:
dat a- t ype Ar r ay- Name[ Ar r ay- Si ze] ;
V d:
i nt arr ay_ i nt [ 8] ;
Lit k mng
Sau khi khai bo mng, ta c th tip cn n mng bng tng phn t thng qua ch sca n.
V d:
char day[ 7] ;
Ch s ca mng khai bo [N] trong C lun lun bt u t 0 v kt thc N-1
Gn gi tr ban u cho mng
Ta c th gn cc gi tr ban u cho tng phn t
day[0] = `S' ;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
53/153
53
day[ 1] = M' ; . . .
hoc tp th nh sau:
i nt ar I nt eger [ 5] = {100, 8, 3, 365, 16};
V d:1: / * I ni t i al i z i ng an arr ay * /2: #i ncl ude 3:4: mai n( )5: {6: i nt i ;7: i nt l i st _ i nt [ 10] ;8:9: f or ( i =0; i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
54/153
-
8/12/2019 Mt s Kin thc c bn v C.pdf
55/153
55
14: pr i nt f ( "The val ue of the f i r st el ement : %d\ n", *pt r _i nt ) ;15: pt r_ i nt = &l i s t_ i nt [ 0] ;16: pr i nt f ( "The addr ess of the f i r st el ement : 0x%p\ n", pt r _i nt ) ;17: pr i nt f ( "The val ue of the f i r st el ement : %d\ n", *pt r _i nt ) ;18: r et ur n 0;19: }
Kt qu:
The st ar t addr ess of t he ar r ay: 0x1802The val ue of t he f i r st el ement : 1The addr ess of t he f i r st el ement : 0x1802The val ue of t he f i r st el ement : 1
Chui k t (String)
Chui k t l mt mng k t vi k t cui cng l k t trng (null - \0).
K t trng (\0) trong C c hiu l FALSE, v cc k t khc null c hiu l TRUE.C th s dng iu xut k t trong an lnh sau:
char st r 2[ ] = "Anot her st r i ng const ant ";i nt i ;/ * pr i nt out str 2 * // * pr i nt out str 2 * /f or ( i =0; str 2[ i ] ; i ++)
pr i nt f ( "%c" , s t r 2[ i ] ) ;
V d:1: / * Pr i nt i ng out an ar r ay of char acters */2: #i ncl ude 3:4: mai n( )5: {6: char arr ay_ch[7] = {`H' , `e' , ` l ' , ` l ' , `o' , ` ! ' , `\ 0' };7: i nt i ;8:9: f or ( i =0; i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
56/153
56
Kt qu:
ar r ay_ch[ 0] cont ai ns: Har r ay_ch[ 1] cont ai ns: ear r ay_ch[ 2] cont ai ns: lar r ay_ch[ 3] cont ai ns: l
ar r ay_ch[ 4] cont ai ns: oar r ay_ch[ 5] cont ai ns: !ar r ay_ch[ 6] cont ai ns:Put al l el ement s t oget her ( Met hod I ) :Hel l o!Put al l el ement s t oget her ( Met hod I I ) :Hel l o!
Mng nhiu chiu
dat a- t ype Ar r ay- Name[ Ar r ay- Si ze1] [ Ar r ay- Si ze2] . . .[ Ar r ay- Si zeN] ;
vi N l s nguyn dng.
Ta c th gn gi tr ban u cho mng nhiu chiu nh sau:ar r ay_i nt [ 0] [ 0] = 1;ar r ay_i nt [ 0] [ 1] = 2;ar r ay_i nt [ 0] [ 2] = 3;ar r ay_i nt [ 1] [ 0] = 4;ar r ay_i nt [ 1] [ 1] = 5;ar r ay_i nt [ 1] [ 2] = 6;
hoc
i nt ar r ay_i nt [ 2] [ 3] = {1, 2, 3, 4, 5, 6};
hoc
i nt ar r ay_i nt [ 2] [ 3] = {{1, 2, 3}, {4, 5, 6}};
V d:1: / * Pr i nt i ng out a 2- D ar r ay */2: #i ncl ude
3:4: mai n( )5: {6: i nt t wo_di m[ 3] [ 5] = {1, 2, 3, 4, 5,7: 10, 20, 30, 40, 50,8: 100, 200, 300, 400, 500};9: i nt i , j ;10:11: f or ( i =0; i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
57/153
57
13: f or ( j =0; j
-
8/12/2019 Mt s Kin thc c bn v C.pdf
58/153
58
20: pr i nt f ( "The si ze of l i st_i nt [ ] [ 3] i s %d byt es. \ n", si zeof( l i st _i nt ) ) ;21: r et ur n 0;22: }
Kt qu:
The si ze of ar r ay_ch[ ] i s 15 byt es.The si ze of l i st _i nt [ ] [ 3] i s 42 byt es.
Bi tp
1. Vi int data[3], c g sai trong cch gn gi tr sau y?data[1] = 1;data[2] = 2;data[3] = 3;
2. Cc mng sau y c kch thc ln bao nhiu?o char array1[3][19];o int array2[];o float array3[][8][16];o char array4[][80];
3. C g sai trong khai bo sau?char l i st_ch[ ] [ ] = {
` A' , ` a' ,` B' , ` b' ,` C' , ` c' ,`D' , `d' ,
`E' , `e' };
XIII. Thao tc vi chui k t (string)
Nidung:
Chui k t l mng k t mt chiu vi phn t cui cng l \0. Vi phn ny ta lmquen vi cc hm thao tc vi chui k t:
Khai bo chui k t Chiu di chui k t Sao chp chui k t c chui k t bng scanf() Hm gets() v puts()
-
8/12/2019 Mt s Kin thc c bn v C.pdf
59/153
59
Khai bo chui k t
char Ar r ay- Name[ Ar r ay- Si ze] ;
char Ar r ay- Name[ ] ;char *Ar r ay- Name;
Mt tp hp k t gii hnbi cp du ngoc kp c ngn ng C xem l mt hngchui k t (string constant). C s t ng thm k t (\0) vo cui dy ch kt thcca chui.
V d: "A character string.", "Hello!" l nhng hng chui k t.
Ta c th gn gi tr cho chui k t bng nhng cch sau:
char ar r _st r [7] = {`H' , `e' , ` l ' , ` l ' , `o' , ` ! ' , `\ 0' };
char st r [ 7] = "Hel l o! ";
char st r[ ] = " I l i ke C. " ;
char *pt r _st r = "I t each mysel f C. ";
Ch :Khng nn khai bo mt bin chui k t m kch thc qu nh so vi mun chng ta
s dng, v nu chng ta gn mt chui di hn bin, c th gy ra nhng li chngtrnh khng nh trc c, m b bin dch s khng bo cho ta bit. V d:char st r [ 6] = "Hel l o! ";
L mt php gn sai (thiu ch cho \0), nhng b bin dch t ng ct i du ! m khngbo g c.
Phn bit c php phn bit gia k t v chui k t:
char ch = `x' ; / *1 byte*/char st r [ ] = "x"; / *2 byt es*/
Ch khi chui k t c biu din di dng char pointer. Ta c th gn trc tip 1chui k t cho mtbin pointer:
char *pt r _str ;pt r _st r = "A char acter st r i ng. ";
V khng th c:
pt r _st r = x' ; / * Sai * /
-
8/12/2019 Mt s Kin thc c bn v C.pdf
60/153
60
Phi sa li nh sau:
char *pt r _str ;*pt r _str = x' ;
V d:1: / * I ni t i al i zi ng st r i ngs * /2: #i ncl ude 3:4: mai n( )5: {6: char st r 1[ ] = {`A' , ` `,7: `s' , `t ' , `r ' , ` i ' , `n' , `g' , ` `,8: `c' , `o' , `n' , ` s' , `t ' , `a' , ` n' , `t ' , `\ 0' };9: char st r 2[ ] = "Anot her st r i ng const ant ";10: char *pt r _str ;11: i nt i ;12:13: / * pr i nt out str 2 */
14: f or ( i =0; str 1[ i ] ; i ++)15: pr i nt f ( "%c" , s t r1[ i ] ) ;16: pr i nt f ( " \ n" ) ;17: / * pr i nt out str 2 */18: f or ( i =0; str 2[ i ] ; i ++)19: pr i nt f ( "%c" , s t r2[ i ] ) ;
20: pr i nt f ( " \ n" ) ;21: / * assi gn a st r i ng t o a poi nt er */22: pt r _st r = "Assi gn a st r i ng t o a poi nt er . ";23: f or ( i =0; *pt r _st r ; i ++)
24: pr i nt f ( "%c", *pt r _st r ++) ;25: r et ur n 0;26: }
Kt qu:
A st r i ng const antAnother st r i ng const antAssi gn a st r i ng t o a poi nt er .
Chiu di chui k t
Hm strlen()#i ncl ude i nt str l en( const char *s);
s l mt bin con tr. Gi tr tr li l s byte ng vi di ca chui k t.
V d:1: / * Measur i ng st r i ng l engt h */
-
8/12/2019 Mt s Kin thc c bn v C.pdf
61/153
61
2: #i ncl ude 3: #i ncl ude 4:5: mai n( )6: {7: char st r 1[ ] = {`A' , ` `,8: `s' , `t ' , `r ' , ` i ' , `n' , `g' , ` `,9: `c' , `o' , `n' , ` s' , `t ' , `a' , ` n' , `t ' , `\ 0' };10: char st r 2[ ] = "Anot her st r i ng const ant ";11: char *pt r _st r = "Assi gn a st r i ng t o a poi nt er . ";12:13: pr i nt f ( "The l engt h of str 1 i s: %d byt es\ n", st r l en( str 1) ) ;14: pr i nt f ( "The l engt h of str 2 i s: %d byt es\ n", st r l en( str 2) ) ;15: pr i nt f ( "The l engt h of t he st r i ng assi gned t o pt r _st r i s: %dbyt es\ n",16: s t r l en(pt r_s t r ) ) ;17: r et ur n 0;18: }
Kt qu:
The l engt h of st r 1 i s: 17 byt esThe l engt h of st r 2 i s: 23 byt esThe l engt h of t he st r i ng ass i gned t o pt r _st r i s: 29 byt es
Sao chp chui k t
Hm strcpy()
#i ncl ude char *st r cpy( char *dest , const char *sr c) ;
Ni dung ca src s c sao li cho dest. Hm strcpy() s tr li gi tr ca src nu thaotc thnh cng.
V d:1: / * Copyi ng st r i ngs */2: #i ncl ude 3: #i ncl ude 4:5: mai n( )6: {7: char st r 1[ ] = "Copy a st r i ng. ";
8: char st r 2[ 15] ;9: char st r 3[ 15] ;10: i nt i ;11:12: / * wi t h str cpy( ) */13: str cpy( str 2, s tr 1) ;14: / * wi t hout st r cpy( ) */15: f or ( i =0; str 1[ i ] ; i ++)16: s t r3[ i ] = s t r1[ i ] ;17: str 3[ i ] = \ 0' ;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
62/153
62
18: / * di spl ay st r 2 and st r 3 */19: pr i nt f ( "The cont ent of st r 2: %s\ n", st r 2) ;20: pr i nt f ( "The cont ent of st r 3: %s\ n", st r 3) ;21: r et ur n 0;22: }
Kt qu:The cont ent of st r 2: Copy a st r i ng.The cont ent of st r 3: Copy a st r i ng.
c v ghi chui k t
Hm gets() v puts()
Hm gets() dng c cc k t t mt giao tip nhp chun (stdin).
#i ncl ude char *get s( char *s) ;
Hm gets() c cc k t gn vo bin s cho n ghi gp EOF v thm vo \0. Nu thnhcng, hm tr li s; nu khng s tr li con tr null.
Hm puts() dng xut cc k t cho mt giao tip xut chun (stdout).
#i ncl ude i nt put s( const char *s) ;
Nu thao tc thnh cng, hm tr li gi tr 0; nu khng s tr li gi tr khc 0. Hm
puts() s thm EOF thay cho k t \0.
V d:1: / * Usi ng get s( ) and put s( ) */2: #i ncl ude 3:4: mai n( )5: {6: char str [ 80] ;7: i nt i , del t = a' - `A' ;8:9: pr i nt f ( "Ent er a st r i ng l ess t han 80 char acters: \ n") ;10: get s( str ) ;11: i = 0;12: whi l e ( str [ i ] ) {13: i f ( ( str [ i ] >= a' ) && ( str [ i ]
-
8/12/2019 Mt s Kin thc c bn v C.pdf
63/153
63
19: r et ur n 0;20: }
Kt qu:
Ent er a st r i ng l ess t han 80 char act er s:Thi s i s a t est .The entered st r i ng i s ( i n uppercase) :THI S I S A TEST.
C th s dng %s trong hm printf() xut mt chui k t ra mnnh.
Hm scanf()
C th s dng hm scanf() c k t t giao tipnhp chun, vi format tng tnh printf().
#i ncl ude i nt scanf ( const char *f or mat , ) ;
Nu thao tc thnh cng, hm tr li s d liu c t stdin; nu khng s tr li EOF.
V d:1: / * Usi ng scanf ( ) */2: #i ncl ude 3:
4: mai n( )5: {6: char str [ 80] ;7: i nt x, y;8: f l oat z;9:10: pr i nt f ( "Ent er t wo i nt eger s separ at ed by a space: \ n") ;11: scanf ( "%d %d" , &x, &y) ;12: pr i nt f ( "Ent er a f l oat i ng- poi nt number : \ n") ;13: scanf ( "%f ", &z) ;14: pr i nt f ( "Ent er a str i ng: \ n") ;15: scanf ( "%s", st r ) ;16: pr i nt f ( "Her e ar e what you' ve ent er ed: \ n") ;
17: pr i nt f ( "%d %d\ n%f \ n%s\ n", x, y, z, st r ) ;18: r et ur n 0;19: }
Kt qu:
Ent er t wo i nt egers separat ed by a space:
-
8/12/2019 Mt s Kin thc c bn v C.pdf
64/153
64
10 12345Ent er a f l oat i ng- poi nt number :1. 234567Ent er a st r i ng:
TestHere ar e what you' ve ent ered:10 123451. 234567
Test
Bi tp
1. Biu thc no sau y ng?o char str1[5] = "Texas";o char str2[] = "A character string";o char str3[2] = "A";o char str4[2] = "TX";
2. Cho bin con tr ptr_ch, Biu thc no sau y ng?o *ptr_ch = `a';o ptr_ch = "A character string";o ptr_ch = `x';o *ptr_ch = "This is Quiz 2.";
3. Vit mt chng trnh tnh di ca mt chui k t bng cch m tng k t.Sau dng hm strlen() so snh.
4. Vit chng trnh s dng scanf() c 2 s nguyn do ngi s dng cho vo,cng 2 s v in tng ln mn nh.
XIV. Phm vi ca bin v lp b nh
Ni dung:
Khi lp trnh chng ta c th gp nhng vn v s trng lp cc bin trong nhng onchng trnh khc nhau. bit cch xc nh phm v hot ng ca chng, ta t m hiu:
Phm vi khi Phm vi hm Phm vi tp Phm vi chng trnh c t auto c t static c t register c t extern const volatile
-
8/12/2019 Mt s Kin thc c bn v C.pdf
65/153
65
Trong C, ta c th khai bo mt bin v ch nh phm vi tip cn n bng cch xc nhphm vi ca n. Cc bin vi phm vi cc b ch c th tip cn c trong khi m nc khai bo. Ta phn bit cc phm vi sau:
Phm vi khi
Trong C, mt khi c gii hn bi ngoc {}. Bin khai bo trong khi c phm vikhi, ngha l n ch hot ng trong khi m thi. Phm vi ny cn gi l cc b, vbin c gi l bin cc b.
V d:
i nt mai n( ){
i nt i ; / * bl ock scope */..
.r et ur n 0;}
hoc v d trong mt khi lng vo nhau:
V d:
1: / * Scopes i n nest ed bl ock */2: #i ncl ude 3:4: mai n( )
5: {6: i nt i = 32; / * bl ock scope 1*/7:8: pr i nt f ( "Wi t hi n t he out er bl ock: i =%d\ n", i ) ;9:10: { / * t he begi nni ng of t he i nner bl ock */11: i nt i , j ; / * bl ock scope 2, i nt i hi des t he out er i nt i * /12:13: pr i nt f ( "Wi t hi n t he i nner bl ock: \ n") ;14: f or ( i =0, j =10; i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
66/153
66
i = 3, j = 7i = 4, j = 6i = 5, j = 5i = 6, j = 4i = 7, j = 3i = 8, j = 2i = 9, j = 1i =10, j = 0Wi t hi n t he out er bl ock: i =32
Phm vi hm
Phmvi hm ch nh mt bin c phm vi hot ng t u n cui mt hm (khngnhm ln vi bin c phm vi khi). Trong C, ch c nhn (label) /v lnh goto l cphm vi hm.
i nt mai n( ){
i nt i ; / * bl ock scope */...st ar t : / * A got o l abel has f unct i on scope */...got o st ar t ; / * t he got o st at ement */...r et ur n 0;
}
Phm vi chng trnh
Bin c phm vi chng trnh khi n c khai bo bn ngoi cc hm. V d:
i nt x = 0; / * pr ogr am scope */f l oat y = 0. 0; / * pr ogr am scope */i nt mai n( ){
i nt i ; / * bl ock scope */..
.r et ur n 0;}
Bin ny cn c gi l bin ton cc.
V d:1: / * Pr ogr am scope vs bl ock scope */2: #i ncl ude
-
8/12/2019 Mt s Kin thc c bn v C.pdf
67/153
67
3:4: i nt x = 1234; / * pr ogr amscope */5: doubl e y = 1. 234567; / * progr amscope */6:7: voi d f uncti on_1( )8: {9: pr i nt f ( "Fr om f unct i on_1: \ n x=%d, y=%f \ n", x, y);10: }11:12: mai n( )13: {14: i nt x = 4321; / * bl ock scope 1*/15:16: f uncti on_1( ) ;17: pr i nt f ( "Wi t hi n t he mai n bl ock: \ n x=%d, y=%f \ n", x, y);18: / * a nest ed bl ock */19: {20: doubl e y = 7. 654321; / * bl ock scope 2 */21: f uncti on_1( ) ;22: pr i nt f ( "Wi t hi n t he nest ed bl ock: \ n x=%d, y=%f \ n" , x, y);
23: }24: r et ur n 0;25: }
Kt qu:
Fr om f uncti on_1:x=1234, y=1. 234567
Wi t hi n the mai n bl ock:x=4321, y=1. 234567
Fr om f uncti on_1:
x=1234, y=1. 234567Wi t hi n t he nest ed bl ock:x=4321, y=7. 654321
TIP
Bin ton cc mc d c nhn thy mi hm trong ton chng trnh, nhng khngnn khai bo s dng nhiu nu khng cn thit, v n s gy tr ngi cho qu trnh dtm li khi debug chng trnh.
Cc c t lp b nhTrong C, lp b nh ca mt bin l cp n phm vi hiu dng ca bin v khng gian ln thi gian. Chnh cc phm vi trn c trng cho tnh khng gian, cn v tnh thigian (tc l hot ng ca bin trong sut thi gian chng trnh chy) s c ch nhbi cc c t sau:
-
8/12/2019 Mt s Kin thc c bn v C.pdf
68/153
68
c t auto
Biu th tnh tm thi ca b nh dnh cho bin. B nh s t ng trng (free) saukhi chng trnh ra khi mt khi no . Tuy nhin t kha ny t dng v hu ht ccbin cc b mc nh l auto.
c t static
Khi mt bin c khai bo static, b nh dnh cho bin s c xc nh vnh vindnh cho bin. Cho nn d ra vo cc khi khc nhau, gi tr trong s khng b xahoc thay i, nu khng phi l lnh chng trnh.
V d:
i nt mai n( ){
i nt i ; / * bl ock scope and t emporary dur at i on */st at i c i nt j ; / * bl ock scope and per manent dur ati on */..r et ur n 0;
}
V d:1: / * Usi ng t he stati c speci f i er */2: #i ncl ude 3: / * t he add_t wo f unct i on */4: i nt add_t wo( i nt x, i nt y)5: {
6: st at i c i nt count er = 1;7:8: pr i nt f ( "Thi s i s t he f uncti on cal l of %d, \ n", count er ++) ;9: r et ur n ( x + y) ;10: }11: / * t he mai n f unct i on */12: mai n( )13: {14: i nt i , j ;15:16: f or ( i =0, j =5; i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
69/153
69
Thi s i s t he f unct i on cal l of 3,t he addi t i on of 2 and 3 i s 5.
Thi s i s t he f unct i on cal l of 4,t he addi t i on of 3 and 2 i s 5.
Thi s i s t he f unct i on cal l of 5,t he addi t i on of 4 and 1 i s 5.
Phm vi tp
Trong C, bin c khai bo l ton ccv staticc gi l c phm vi tp.
i nt x = 0; / * pr ogr am scope */stati c i nt y = 0; / * f i l e scope */stat i c f l oat z = 0. 0; / * f i l e scope */i nt mai n( ){
i nt i ; / * bl ock scope */...r et ur n 0;
}
c t register
Register (thanh ghi) l mt dng b nh trong CPU thc hin cc chc nng c bittrong tnh ton v lu tr d liu tm thi trong qu trnh x l. V nm trong CPU nnd liu lu tr trn register s c tip cn nhanh hn. Cho nn, trong qu trnh lp
trnh, c mt s thao tc cn x l nhanh, ta c th s dng thanh ghi. V ngn ng C toiu kin cho ta c th khai bo bin trn thanh ghi bng c t register.
i nt mai n( ){
/ * bl ock scope wi t h t he r egi st er speci f i er */regi s ter i nt i ;. . .f or ( i =0; i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
70/153
70
i nt x = 0; / * a gl obal var i abl e */ext er n i nt y; / * an al l usi on t o a gl obal var i abl e y */i nt mai n( ){
ext er n i nt z; / * an al l usi on t o a gl obal var i abl e z */i nt i ; / * a l ocal var i abl e * /...r et ur n 0;
}
T kha const
N ta khai bo mt bin vi const, gi tr ca n s khng thay i trong sut chngtrnh.
const doubl e ci r cl e_r ati o = 3. 141593;const char st r [ ] = "A st r i ng const ant ";
char const *pt r _st r = "A st r i ng const ant ";
T kha volatile
C tc dng lu b bin dch, l bin khai bo vi volatilec th b thay i mt cchno ngoi chng trnh (ng h my nhy t ng, b nh thit b cnh bo), vb bin dch s khng kim tra trng thi b nh dnh cho bin trong qu trnh thaotc thc hin chng trnh.
voi d read_keyboar d( ){
vol at i l e char keyboar d_ch; / * a vol at i l e var i abl e */...
}
Bi tp
1. Phn lai cc bin xuthin trong on chng trnh sau?i nt x = 0;f l oat y = 0. 0;i nt myFunct i on( )
{i nt i , j ;f l oat y;. . .{
i nt x , y;. . .
}. . .
-
8/12/2019 Mt s Kin thc c bn v C.pdf
71/153
71
}
2. Hy nhn dng cc lp b nh ca cc khai bo trong on chng trnh sau:i nt i = 0;s tat i c i nt x;
ext er n f l oat y;i nt myFunct i on( ){
i nt i , j ;ext er n f l oat z;r egi ster l ong s;stat i c i nt i ndex;const char st r [ ] = "Warni ng message. " ;. . .
}
3. Chy chng trnh sau y, xem ci g xut hin ln mn nh v gii thch tisao?
#i ncl ude i nt mai n( ){
i nt i ;
f or ( i =0; i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
72/153
72
dat a_t ype_speci f i er f unct i on_name( ) ;
Vi data_type_specifier nh kiu m hm s tr li gi tr, function_name l tn hmtheo quy tc ca C.
hoc
dat a_t ype_speci f i er f unct i on_name(dat a_t ype_speci f i er argument _name1,dat a_t ype_speci f i er argument _name2,dat a_t ype_speci f i er argument _name3,...dat a_t ype_speci f i er argument _nameN,
) ;
Vi argument_name1, argument_name2, l cc nguyn mu (prototypes) ca i s s
trao i gi tr vi hm.
Nu hm c nh ngha trc khi hm c gi, ta khng cn khai bo. Nu khng,bng cch no compiler hiu hm c tn ti, tc l phi c dng khai bo hmtrc khi dng, hoc dng #include header.h (thng tin v khai bo cc hm c nhngha thnh th vin)
Cch gi hm cng nh thc hin mt cu lnh.
V d:
1: / * Maki ng f uncti on cal l s */2: #i ncl ude 3:4: i nt f unct i on_1( i nt x, i nt y) ;5: doubl e f unct i on_2( doubl e x, doubl e y)6: {7: pr i nt f ( "Wi t hi n f uncti on_2. \ n") ;8: ret urn ( x - y) ;9: }10:11: mai n( )12: {13: i nt x1 = 80;14: i nt y1 = 10;15: doubl e x2 = 100. 123456;16: doubl e y2 = 10. 123456;17:18: pr i nt f ( "Pass f unct i on_1 %d and %d. \ n" , x1, y1) ;19: pr i nt f ( "f uncti on_1 r et ur ns %d. \ n", f uncti on_1( x1, y1) ) ;20: pr i nt f ( "Pass f unct i on_2 %f and %f . \ n", x2, y2) ;21: pr i nt f ( "f uncti on_2 r et ur ns %f . \ n", f uncti on_2( x2, y2) ) ;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
73/153
73
22: r et ur n 0;23: }24: / * f uncti on_1( ) def i ni t i on */25: i nt f uncti on_1( i nt x, i nt y)26: {27: pr i nt f ( "Wi t hi n f uncti on_1. \ n") ;28: r et ur n ( x + y);29: }
Kt qu:
Pass f unct i on_1 80 and 10.Wi t hi n f unct i on_1.f unct i on_1 r et ur ns 90.Pass f unct i on_2 100. 123456. and 10. 123456.Wi t hi n f unct i on_2.f unct i on_2 r et ur ns 90. 000000.
Cc dng hm mu
Hm khng i sdat a_t ype_speci f i er f unct i on_name( )dat a_t ype_speci f i er f unct i on_name( voi d)
V d:i nt get char ( voi d) ;
i nt c;c = get char ( ) ;
V d:
1: / * Funct i ons wi t h no argument s */2: #i ncl ude 3: #i ncl ude 4:5: voi d GetDateTi me( voi d) ;6:7: mai n( )8: {9: pr i nt f ( "Bef or e t he Get Dat eTi me( ) f uncti on i s cal l ed. \ n") ;10: GetDateTi me( ) ;
11: pr i nt f ( "Af t er t he Get Dat eTi me( ) f uncti on i s cal l ed. \ n") ;12: r et ur n 0;13: }14: / * Get Dat eTi me( ) def i ni t i on */15: voi d GetDat eTi me(voi d)16: {17: t i me_t now;18:19: pr i nt f ( "Wi t hi n Get Dat eTi me( ) . \ n") ;20: t i me(&now) ;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
74/153
74
21: pr i nt f ( "Cur r ent dat e and t i me i s: %s\ n",22: asct i me( l ocal t i me( &now) ) ) ;23: }
Kt qu:
Bef or e t he Get Dat eTi me( ) f unct i on i s cal l ed.Wi t hi n Get DateTi me( ) .Cur r ent dat e and t i me i s: Sat Apr 05 11: 50: 10 1997Af t er t he Get Dat eTi me( ) f unct i on i s cal l ed.
S dng time(), localtime(), and asctime()
Mt s hm th vin C cho bit thi gian:
Trong C, ham time() tr li thi gian theo lch biu din bng s n v xc nh bi kiutime_t k t 1 thi im no .
#i ncl ude t i me_t t i me( t i me_t *t i mer ) ;
Hm localtime() chuyn i thi gian tnh bng time() thnh thi gian a phng biudin di dng cu trc struct tm.
#i ncl ude st r uct t m *l ocal t i me( const t i me_t *t i mer ) ;
Hm asctime() chuyn i thi gian theo cu trc struct tm thnh dng ASCII (nh SatApr 05 11:50:10 1997 chng hn)
#i ncl ude char *asct i me( const st r uct t m *t i mept r ) ;
V d minh ha c th xem on code trn.
Hm vi s i s c nh
V d:
i nt f unct i on_1( i nt x , i nt y) ;
Mu hm vi s i s thay i
V d:
i nt pr i nt f ( const char *f or mat [ , ar gument , . . . ] ) ;
Khai bo chung:
-
8/12/2019 Mt s Kin thc c bn v C.pdf
75/153
75
dat a_t ype_speci f i er f unct i on_name(data_t ype_speci f i er argument _name1, . . .
) ;
Khi nim lp trnh cu trc (lp trnh th tc)
Lp trnh cu trc t c s trn vic xy dng cc hm hay cc th tc. Lp trnh cutrc c 2 cch tip cn: di ln (bottom-up) v trn xung(top-down).
Cch di ln: chia chng trnh thnh nhng khi nh, nh ngha thnh cc hm; saukhi vit v th nghim xong s kt hp li thnh chng trnh chnh.
Cch trn xung: bt u lm vic t chng trnh chnh (main() chng hn). Khi cchm con pht sinh, s tun t vit sau.
Dng phng php kt hp mt cch ti u c hai l kh nng ph thuc vo dykhinh nghim ca lp trnh vin.
Bi tp
1. Biu thc no sau y l khai bo hm:i nt f unct i on_1( i nt x , i nt y) ;i nt f uncti on_2( i nt x, i nt y) {r et ur n x+y; }
2. Cc khai bo no sau y l sai:o double function_1(int x, ...);o void function_2(int x, int y, ...);o char function_3(...);o int function_4(int, int, int, int);
3. Khai bo v nh ngha hm MultiTwo() nhn 2 s nguyn vi nhau. Vit chngtrnh s dng hm trn v in kt qu ln mn nh.
XVI. S dng con tr
Ni dung:
Php tnh s hc con tr Con tr v mng Chuyn mng cho hm Chuyn con tr cho hm Con tr ch n hm
-
8/12/2019 Mt s Kin thc c bn v C.pdf
76/153
76
Php tnh s hc con tr
Trong C, ta c th chuyn v tr con tr bng cch cng hoc tr s nguyn t v tr ca
con tr. Format chung:
poi nt er _name + n
Vi n l s integer (+) hoc (-); pointer_name c nh ngha bi
dat a_t ype_speci f i er *poi nt er _name;
Php ton s hc trn s dch chuyn con tr n v tr mi ng vi
poi nt er _name + n * si zeof ( dat a_t ype_speci f i er )
V d:1: / * Poi nt er ar i t hmet i c */2: #i ncl ude 3:4: mai n( )5: {6: char *pt r _ch;7: i nt *pt r _ i nt ;8: doubl e *ptr _db;9: / * char poi nt er pt r _ch */10: pr i nt f ( "Cur r ent posi t i on of pt r _ch: 0x%p\ n", pt r _ch) ;11: pr i nt f ( "The posi t i on af t er pt r _ch + 1: 0x%p\ n", pt r _ch + 1) ;12: pr i nt f ( "The posi t i on af t er pt r _ch + 2: 0x%p\ n", pt r _ch + 2) ;13: pr i nt f ( "The posi t i on af t er pt r _ch - 1: 0x%p\ n", ptr _ch - 1) ;
14: pr i nt f ( "The posi t i on af t er pt r _ch - 2: 0x%p\ n", ptr _ch - 2) ;15: / * i nt poi nt er pt r_ i nt * /16: pr i nt f ( "Cur r ent posi t i on of pt r _i nt : 0x%p\ n", pt r _i nt ) ;17: pr i nt f ( "The posi t i on af t er pt r _i nt + 1: 0x%p\ n", pt r _i nt + 1) ;18: pr i nt f ( "The posi t i on af t er pt r _i nt + 2: 0x%p\ n", pt r _i nt + 2) ;19: pr i nt f ( "The posi t i on af t er pt r _i nt - 1: 0x%p\ n", pt r _i nt - 1) ;20: pr i nt f ( "The posi t i on af t er pt r _i nt - 2: 0x%p\ n", pt r _i nt - 2) ;21: / * doubl e poi nt er pt r _ch */22: pr i nt f ( "Cur r ent posi t i on of pt r _db: 0x%p\ n", pt r _db) ;
23: pr i nt f ( "The posi t i on af t er pt r _db + 1: 0x%p\ n", pt r _db + 1) ;24: pr i nt f ( "The posi t i on af t er pt r _db + 2: 0x%p\ n", pt r _db + 2) ;25: pr i nt f ( "The posi t i on af t er pt r _db - 1: 0x%p\ n", pt r _db - 1) ;26: pr i nt f ( "The posi t i on af t er pt r _db - 2: 0x%p\ n", pt r _db - 2) ;27:28: r et ur n 0;29: }
p s:
-
8/12/2019 Mt s Kin thc c bn v C.pdf
77/153
77
Cur r ent posi t i on of pt r _ch: 0x000BThe posi t i on af t er pt r _ch + 1: 0x000CThe posi t i on af t er pt r _ch + 2: 0x000DThe posi t i on af t er pt r _ch - 1: 0x000AThe posi t i on af t er pt r _ch - 2: 0x0009Cur r ent posi t i on of pt r _i nt : 0x028B
The posi t i on af t er pt r _i nt + 1: 0x028DThe posi t i on af t er pt r _i nt + 2: 0x028FThe posi t i on af t er pt r _i nt - 1: 0x0289The posi t i on af t er pt r _i nt - 2: 0x0287Cur r ent posi t i on of pt r _db: 0x0128
The posi t i on af t er pt r _db + 1: 0x0130The posi t i on af t er pt r _db + 2: 0x0138The posi t i on af t er pt r _db - 1: 0x0120The posi t i on af t er pt r _db - 2: 0x0118
Cnh boCon tr l mt cng c lp trnh rt mnh, nhng nu s dng khng thnh thc v cn
thn rt d sinh ra nhng li chng trnh rt kh tm. V d: ta thng gn ni dung bincho mt pointer thay v a ch ca n, nhng phn ln cc compiler C thng bo li ny.Mt v d khc: s dng pointer khng xc nh trc.
i nt x, pt r _ i nt ;x = 8;*pt r _i nt = x;
Ptr_int khng c xc nh trc, nu ta gn ni dung 8 cho n, c th n s chp chngln mt v tr no cha bit trong b nh lm sai d liu ca mt bin no lu vo vtr trc y.Cho nn, nht thit phi khai bo trc, chng hn:i nt x, pt r _ i nt ;x = 8;
pt r _i nt = &x; / * i ni t i al i ze t he poi nt er */
Phep hiu con trptr_str2 - ptr_str1
Php hiu trn cho ta offset a ch ng vi a ch 2 con tr ptr_str1 v ptr_str2. Ttnhin ch c cc con tr c cng kiu d liu mi thc hin c.
V d:1: / * Poi nt er subt r acti on */2: #i ncl ude
3:4: mai n( )5: {6: i nt *pt r _ i nt 1, *pt r _ i nt 2;7:8: pr i nt f ( "The posi t i on of pt r _i nt 1: 0x%p\ n", pt r _i nt 1) ;9: pt r _i nt 2 = pt r _i nt 1 + 5;10: pr i nt f ( "The posi t i on of pt r _i nt 2 = pt r _i nt 1 + 5: 0x%p\ n",pt r _ i nt 2) ;
-
8/12/2019 Mt s Kin thc c bn v C.pdf
78/153
78
11: pr i nt f ( "The subt r acti on of pt r _i nt 2 - pt r _i nt 1: %d\ n", pt r _i nt 2-
pt r _ i nt1) ;12: pt r _i nt 2 = pt r _i nt 1 - 5;13: pr i nt f ( "The posi t i on of pt r _i nt 2 = pt r _i nt 1 - 5: 0x%p\ n",pt r _ i nt 2) ;14: pr i nt f ( "The subt r acti on of pt r _i nt 2 - pt r _i nt 1: %d\ n", pt r _i nt 2-
pt r _ i nt1) ;15:16: r et ur n 0;17: }
p s:
The posi t i on of pt r _i nt 1: 0x0128The posi t i on of pt r _i nt 2 = pt r _i nt 1 + 5: 0x0132The subt r act i on of pt r _i nt 2 - pt r _i nt 1: 5The posi t i on of pt r _i nt 2 = pt r _i nt 1 - 5: 0x011EThe subt r act i on of pt r _i nt 2 - pt r _i nt 1: - 5
Con tr v mng
Bi v tn mng khng c ch s c hiu nh l con tr ch n phn t u tin camng, ta c th tip cn n mng thng qua con tr truy cp phn t u tin vcc phn t tip theo thng qua php tnh s hc con tr.
pt r _ar r ay = ar r ay;
v array[n] tng ngvi
*( pt r _arr ay + n)
V d:1: / * Accessi ng ar r ays vi a poi nt er s */2: #i ncl ude 3:4: mai n( )5: {6: char str [ ] = " I t ' s a str i ng!" ;7: char *pt r _str ;8: i nt l i s t [ ] = {1, 2, 3, 4, 5};9: i nt *pt r _ i nt ;10:11: / * access char ar r ay */12: pt r _str = str ;13: pr i nt f ( "Bef or e t he change, str cont ai ns: %s\ n", st r ) ;14: pr i nt f ( "Bef or e t he change, st r [ 5] cont ai ns: %c\ n", str [ 5] ) ;15: *( pt r _st r + 5) = A' ;16: pr i nt f ( "Af t er t he change, st r [ 5] cont ai ns: %c\ n", st r [ 5] ) ;17: pr i nt f ( "Af t er t he change, st r cont ai ns: %s\ n", str ) ;18: / * access i nt ar r ay */
-
8/12/2019 Mt s Kin thc c bn v C.pdf
79/153
79
19: pt r_ i nt = l i s t ;20: pr i nt f ( "Bef or e t he change, l i st[ 2] cont ai ns: %d\ n", l i st[ 2] ) ;21: *( pt r _i nt + 2) = - 3;22: pr i nt f ( "Af t er t he change, l i st[ 2] cont ai ns: %d\ n", l i st[ 2] ) ;23:24: r et ur n 0;25: }
p s:
Bef or e t he change, st r cont ai ns: I t ' s a st r i ng!Bef or e t he change, st r [ 5] cont ai ns: aAf t er t he change, st r [ 5] cont ai ns: AAf t er t he change, st r cont ai ns: I t ' s A st r i ng!Bef or e t he change, l i st [ 2] cont ai ns: 3Af t er t he change, l i st [ 2] cont ai ns: - 3
Con tr v Hm
Chuyn mng cho hm
chuyn mng cho hm, ta to i s chnh bng mng vi cch vitFunct i onName(dat atype l i st name[ ] ) .
V d:1: / * Passi ng ar r ays t o f uncti ons */2: #i ncl ude 3:4: i nt AddThree( i nt l i s t [ ] ) ;5:6: mai n( )7: {8: i nt sum, l i s t [ 3] ;9:10: pr i nt f ( "Ent er t hr ee i nt eger s separ at ed by spaces: \ n") ;11: scanf ( "%d%d%d", &l i st [ 0] , &l i st [ 1] , &l i st [ 2] ) ;12: sum = AddThr ee( l i st ) ;13: pr i nt f ( "The sum of the t hr ee i nt eger s i s: %d\ n", sum) ;14:15: r et ur n 0;16: }17:18: i nt AddThr ee( i nt l i st[ ] )19: {
20: i nt i ;21: i nt r esul t = 0;22:23: f or ( i =0; i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
80/153
80
Ent er t hr ee i nt eger s separated by spaces:10 20 30
The sum of t he t hree i nt eger s i s: 60
Chuyn con tr cho hmMt mng khng ch s c hiu nh mt con tr ch n phn t u tin. Cho nn tacng c th chuyn mng cho hm bng cch chuyncon tr tng ng cho hm.
V d:1: / * Passi ng poi nt er s t o f uncti ons */2: #i ncl ude 3:4: voi d ChPr i nt ( char *ch) ;5: i nt Dat aAdd( i nt *l i st, i nt max) ;6: mai n( )
7: {8: char str [ ] = " I t ' s a str i ng!" ;9: char *pt r _str ;10: i nt l i st[ 5] = {1, 2, 3, 4, 5};11: i nt *pt r _ i nt ;12:13: / * assi gn addr ess t o poi nt er */14: pt r _str = str ;15: ChPr i nt ( pt r_st r ) ;16: ChPr i nt ( str ) ;17:18: / * assi gn addr ess t o poi nt er */19: pt r_ i nt = l i s t ;20: pr i nt f ( "The sum r et ur ned by Dat aAdd( ) : %d\ n",21: Dat aAdd( pt r _i nt , 5) ) ;22: pr i nt f ( "The sum r et ur ned by Dat aAdd( ) : %d\ n",23: Dat aAdd( l i st, 5) ) ;24: r et ur n 0;25: }26: / * f uncti on def i ni t i on */27: voi d ChPr i nt ( char *ch)28: {29: pr i nt f ( "%s\ n", ch) ;30: }31: / * f uncti on def i ni t i on */32: i nt Dat aAdd( i nt *l i st , i nt max)33: {
34: i nt i ;35: i nt sum = 0;36:37: f or ( i =0; i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
81/153
-
8/12/2019 Mt s Kin thc c bn v C.pdf
82/153
82
p s:
The sum r et urned by Dat aAdd1( ) : 30The sum r et urned by Dat aAdd2( ) : 30
Mng con tr
V d:
i nt *pt r _ i nt [ 3] ;
bin ptr_int l mt mng 3 phn t con tr ch n s nguyn.
i nt x1 = 10;i nt x2 = 100;i nt x3 = 1000;
pt r _i nt [ 0] = &x1;pt r _i nt [ 1] = &x2;pt r _i nt [ 2] = &x3;
V d:1: / * Usi ng an ar r ay of poi nt er s */2: #i ncl ude 3: / * f uncti on decl ar at i ons */4: voi d St rPr i nt 1( char **st r1, i nt s i ze) ;5: voi d St r Pr i nt 2( char *str 2) ;6: / * mai n( ) f uncti on */7: mai n( )
8: {9: char *st r [ 4] = {"Ther e' s musi c i n t he si ghi ng of a r eed; " ,10: "Ther e' s musi c i n t he gushi ng of a r i l l ; ",11: "Ther e' s musi c i n al l t hi ngs i f men had ear s; ",12: "Ther e eart h i s but an echo of t he spher es. \ n"13: };14: i nt i , s i ze = 4;15:16: St r Pr i nt 1(s t r , s i ze) ;17: f or ( i =0; i
-
8/12/2019 Mt s Kin thc c bn v C.pdf
83/153
83
32: {33: / * Pr i nt s one st r i ng at a t i me */34: pr i nt f ( "%s\ n", s tr 2) ;35: }
p s:
There' s musi c i n t he si ghi ng of a r eed;There' s musi c i n t he gushi ng of a r i l l ;There' s musi c i n al l t hi ngs i f men had ear s;There ear t h i s but an echo of t he spheres.There' s musi c i n t he si ghi ng of a r eed;There' s musi c i n t he gushi ng of a r i l l ;There' s musi c i n al l t hi ngs i f men had ear s;There ear t h i s but an echo of t he spheres.
Con tr ch n hm
Tng t nh mng, tn hm khng c i s c hiu nh con tr ch n phn b nhcha gi tr ca hm. Ta c th khai bo con tr ch n gi tr ca hm v tip cn hm thng qua con tr va khai bo.
V d:1: / * Poi nt i ng t o a f uncti on */2: #i ncl ude 3: / * f uncti on decl ar at i on */4: i nt St r Pr i nt ( char *st r ) ;5: / * mai n( ) f uncti on */6: mai n( )7: {8: char st r [ 24] = "Poi nt i ng t o a f uncti on. ";
9: i nt ( *pt r ) (char *st r ) ;10:11: pt r = St r Pr i nt ;12: i f ( ! ( * pt r ) ( s t r ) )13: pr i nt f ( "Done!\ n") ;14:15: r et ur n 0;16: }17: / * f uncti on def i ni t i on */18: i nt St r Pr i nt ( char *st r )19: {20: pr i nt f ( "%s\ n", s tr ) ;21: r et ur n 0;
22: }
p s:
Poi nt i ng t o a f uncti on.Done!
-
8/12/2019 Mt s Kin thc c bn v C.pdf
84/153
84
Bi tp
1. Ta phi cng thm bao nhiu byte cho cc php tnh sau?o ptr_ch + 4o ptr_int + 2o ptr_flt + 1o ptr_ch + 12o ptr_int + 6o ptr_flt + 3
2. Cho on khai bo sau:char ch[ ] = {`a' , `b' , `c' , `d' , `A' , `B' , `C' , `D' };char *pt r ;pt r = &ch[ 1] ;
cc biu thc sau y cho kt qu g ?
o *(ptr + 3)o ptr - cho *(ptr - 1)o *ptr = `F'
3. Cho mng k t sau:char st r [ 2] [ 15] = { "You know what , ", "C i s power f ul . " };
vit chng trnh chuyn a ch khi u ca str cho hm ri in ni dung str lnmn nh.
XVII. nh v b nh ng
Ni dung:
Trong phn ny ta hc cch khai bo v nh v b nh ng - mt phn b nh sdng trong chng trnh trong qu trnh chy chng trnh (runtime). Trong C c 4hm chnh sau:
malloc() calloc() realloc() free()
-
8/12/2019 Mt s Kin thc c bn v C.pdf
85/153
85
Hm malloc()
Dng nh v mt khong b nh c trng.
#i ncl ude voi d *mal l oc(si ze_t s i ze) ;
size ch s byte s nh v. Hm s tr li mt con tr void. Nu khng b nh, hm str li con tr NULL.
V d:1: / * Usi ng t he mal l oc f unct i on */2: #i ncl ude 3: #i ncl ude 4: #i ncl ude 5: / * f uncti on decl ar at i on */6: voi d St r Copy( char *st r 1, char *st r 2) ;7: / * mai n( ) f uncti on */8: mai n( )9: {10: char str [ ] = "Use mal l oc( ) to al l ocat e memor y. ";11: char *pt r _str ;12: i nt r esul t ;13: / * cal l mal l oc( ) * /14: pt r _st r = mal l oc( st r l en( st r ) + 1) ;15: i f ( pt r _st r ! = NULL){16: St r Copy( str , pt r _str ) ;17: pr i nt f ( "The st r i ng poi nt ed t o by pt r _st r i s: \ n%s\ n",18: pt r_s t r ) ;19: r esul t = 0;20: }
21: el se{22: pr i nt f ( "mal l oc( ) f unct i on f ai l ed. \ n") ;23: r esul t = 1;24: }25: r et ur n r esul t ;26: }27: / * f uncti on def i ni t i on */28: voi d St r Copy( char *st r 1, char *st r 2)29: {30: i nt i ;31:32: f or ( i =0; str 1[ i ] ; i ++)33: s t r2[ i ] = s t r1[ i ] ;34: str 2[ i ] = \ 0' ;35: }
Kt qu:
The st r i ng poi nt ed t o by pt r _st r i s:Use mal l oc( ) t o al l ocat e memory.
Hm free()
-
8/12/2019 Mt s Kin thc c bn v C.pdf
86/153
86
Hm dng gii phng phn b nh nh v trc y bng lnh malloc() dngvo vic khc nu khng s dng na.
V d:1: / * Usi ng t he f r ee( ) f uncti on */
2: #i ncl ude 3: #i ncl ude 4: / * f uncti on decl ar at i ons */5: voi d Dat aMul t i pl y( i nt max, i nt *pt r ) ;6: voi d Tabl ePr i nt ( i nt max, i nt *pt r ) ;7: / * mai n( ) f uncti on */8: mai n( )9: {10: i nt *pt r _i nt , max;11: i nt t er mi nat i on;12: char key = `c' ;13:14: max = 0;15: t er mi nat i on = 0;
16: whi l e ( key ! = `x' ) {17: pr i nt f ( "Ent er a si ngl e di gi t number : \ n") ;18: scanf ( "%d", &max) ;19:20: pt r _i nt = mal l oc( max * max * si zeof ( i nt ) ) ; / * cal l mal l oc( )*/21: i f ( pt r _i nt ! = NULL){22: Dat aMul t i pl y( max, pt r _i nt ) ;23: Tabl ePr i nt ( max, pt r _i nt ) ;24: f ree(pt r _ i nt ) ;25: }26: el se{27: pr i nt f ( "mal l oc( ) f unct i on f ai l ed. \ n")