pointers variables and memory address

89
1 Pointers Variables and Memory Address When a variable (of type int, double, char, etc.) is declared in a C program code, the operating system allocates a location for the variable somewhere in the memory. The value of the variable is stored at this location. int num = 0; 1000 num 1002 The address of the variable num 1004 1006 1008 1010 An address (e.g. 1002), assigned to the variable, id entifies the memory location of that variable. Every time the variable is 0

Upload: bin

Post on 12-Feb-2016

59 views

Category:

Documents


4 download

DESCRIPTION

Pointers Variables and Memory Address When a variable (of type int, double, char, etc.) is declared in a C program code, the operating system allocates a location for the variable somewhere in the memory. The value of the variable is stored at this location. int num = 0; 1000 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Pointers Variables and Memory Address

1

Pointers Variables and MemoryAddress

When a variable (of type int, double, char, etc.) is declared in a C program code, the operating system allocates a locati on for the variable somewhere in the memory. The value of the

variable is stored at this location. 0int num = ;

1000 num TTT 1002TTTTTTT TT TTT TTTTTTTT TTT

1004100610081010

An address (e.g. 1 0 0 2 ), assigned to the variable, identifie s t he memory location of that variable. Every time the variable is

used in a program, the operating system goes to that location and reads and modifies dataaccordingly.

0

Page 2: Pointers Variables and Memory Address

2

Variables and MemoryAddress So far, we have not been concerned about memory

addresses. However, C l anguage off er s a powerful tool to access and manipulate the addresses of variables by means

ofpoi nt er s. The & (address of)operator

Recall the use of the scanffunction:scanf(“%d”,&num); The & operator, evaluates the address of the variable num.

In the previous example: &num is equal to 1 0 0 2 .

Page 3: Pointers Variables and Memory Address

3

Pointers• A pointer is a variable, but unlike the other types of

variables that we have seen, it contains a memory address as its value.• This memory address is

usually the address of another variable. To declare a pointer variable, a “* ” should be put

before the name: *int p; /* p is a pointer to an integer i.e., it

can keep the address of an integer variable */

double *dd; */ dd is a pointer to a double

variable*/

Page 4: Pointers Variables and Memory Address

4

Pointersint num; 1000 num = 0; 1002pointerint *ptr_num; 1004 declaration ptr_num = # 1006 1008 1010• ptr_num is declared as a pointer to an integer variable.• then, it is assigned the address of the integer variable num which was declaredbefore.• ptr_num “ indirectlyreferences ” the value of the variable num.

ptr_num = bbb 0 * 0ptr_num =

/

0

1002

num

ptr_num

Page 5: Pointers Variables and Memory Address

5

Pointers& mean “address of” or “point at”* mean value of “what am I pointing at”num 0

ptr_num 1002*ptr_num num 0 # 1002 1002&*ptr_numptr_numptr_num is a pointer to the integer variable num:

*ptr_num is equal to 0 (the value of num) ptr_num indirectly references the value 0.

/

ptr_num

num0

Page 6: Pointers Variables and Memory Address

6

Pointer Types• Pointers can be declared to

point to variables of any type.Examples:

int * ptr_num1 ; (pointer to an integer or integer

poi nt er ). double * ptr_num2 ;

(pointer to a floating point number).

char *ptr_letter; (pointer to a character).

Page 7: Pointers Variables and Memory Address

7

Example Program # include <stdio.h> int main ( ){1002 int num1 , num2 , product;1004 int * ptr_num1 , * ptr_num2 ;1006 num1 = 5 ;1008 num2 = 7 ;1010 ptr_num1 = &num1 ;1012 ptr_num2 = &num2 ;1014 product = num1 * ( * ptr_num2 ); printf(“The address of num1 is %p\n”, &num1 ); printf(“The value of ptr_num1 is 1%p\n”, ptr_num ); TTTTT TT TTT T TT 1 1%d\n”, num ); * 1printf(“The value of ptr_num * 1is %d\n”, ptr_num ); printf(“The value of product TT TTTTTT TToduct);return 0;}

num1productnum2

ptr_num1ptr_num2

Page 8: Pointers Variables and Memory Address

8

Brain Exercise on Pointers What is the output of the

following code segment?#include<stdio.h>

void main() { 5 0 1 2 3 4int x[ ] = { , , , , }; *int yptr, i;

yptr = &x[1]; 0 3for ( i= ; i< ; i++)

-yptr[ i ] = 1; 0 5for (i= ; i< ; i++)

printf(“%d ”, x[i]);} - - - 0 1 1 1 4

Page 9: Pointers Variables and Memory Address

9

Exercise # include <stdio.h>

void main(){ double x[4 ] = {1 .0 ,

2.0, 3.0, 4.0}; *double xptr;

int k; 2xptr = &x[ ];

-* 1 10(xptr+ ) = . ; for (k=0; k<4; k++)

printf(“%f ”, x[k]);} -1.0 2.0 3.0 1.0

Page 10: Pointers Variables and Memory Address

10

พอยนเตอร (Pointer)Pointer คอ ตวแปรชนดหนงททำ� หน�ทเกบตำ�แหนงทอย

( address) ของตวแปรแทนทจะเกบขอมล ต�งๆก�รกำ�หนดชนดของตวแปรพอยนเตอร

ตวแปรทจะทำ�หน�ทเปนตวแปรพอยนเตอรจะตองมก�รกำ�หนดไวกอนตอนตนของโปรแกรมโดยมรปแบบดงน

type *var_name type - ชนดของตวแปร

* - เปนเครองหม�ยทแสดงว�ตวแปรทต�มหลง เครองหม�ยนเปนตวแปรPointer

var _name - ชอตวแปรตวอย�ง int *a

Page 11: Pointers Variables and Memory Address

11

เครองหม�ยทใชในตวแปรพอยนเตอร 1. เครองหม�ย & เปนเครองหม�ยทใชสำ�หรบใหค�

ตำ�แหนงทอย ( address ) ของตวแปรซง อยหลงเครองหม�ย &ตวอย�ง

int a = 5 , *b;b = &a;

ค�ในหนวยคว�มจำ�a b

ค�ขอมล 5 1000address 1000

Page 12: Pointers Variables and Memory Address

12

เครองหม�ยทใชในตวแปรพอยนเตอร ( ตอ) 2. เครองหม�ย * จะใหค�ของขอมลซงเกบอยใน

ตำ�แหนงทอย (address) ทตวแปรPointer นนชอยออกม�ตวอย�ง

int a , b , *c;a = 10;c = &a;b = *c;

ค�ในหนวยคว�มจำ�a c b

ค�ขอมล 10 2000 10address 2000

Page 13: Pointers Variables and Memory Address

13

ตวแปรพอยนเตอรททำ�หน�ทเปน Pointer เปนก�รกำ�หนดตวแปร Pointer ใหส�ม�รถเกบตำ�แหนงท

อย (address) ของตวแปร Pointer อก ตวหนง ลกษณะแบบนอ�จ เรยกว� Indirect pointer

ตวแปร pointer_1pointer_2 ก�รกำ�หนดตวแปร pointer ของ pointer มรปแบบดงน

type **pointer_var

Page 14: Pointers Variables and Memory Address

14

ตวอย�ง * 1 ** 2int a , p_ , p_ ; int b;

15a = ; 1p_ = &a; 2 1p_ = &p_ ;

b = **p_2; T 1p_ 2p_b

15 1000 200015addr ess 1000 20003000

Page 15: Pointers Variables and Memory Address

15

Functions:Introduction• Functions are the

program modules written to perform a specific task or

a collection of tasks.• For example, printf that we used in previous lectures is a function to

display a given string on the screen.

Page 16: Pointers Variables and Memory Address

16

Function Calls Format :

FunctionName( argumentlist );

Arguments may be• constants• variables• expressions

Argument list consists of arguments separated by commas. .

Page 17: Pointers Variables and Memory Address

17

Function Calls• Functions may be called

as a part of assignment: Example: y=sqrt(x);

Here sqrt is a predefined function which takes the sq

uare root of its argument. In the above statement, the va lue calculated by sqrt is assi

gned to y.• Functions may be called

without an assignment: Example: printf(“HelloWorld”);

Page 18: Pointers Variables and Memory Address

18

Functions:Classification• We can classify functions

into two main groups:• (Predefined) Library

Functions: Example : printf

• User Defined Functions: We’ll learn how to write ou r own functions…

Page 19: Pointers Variables and Memory Address

19

(Predefined) LibraryFunctions• Functions that are

implemented as a part of C toolkit.

Example: printf• If a library function is used, then the corresponding header file should be included at the top of the program using

preprocessor directive. Example:

# include <stdio. h> for printf function.

Page 20: Pointers Variables and Memory Address

20

Some Mathematical Library Functions Defined in math.h

bbbbbbbb Purpose double ceil (doublex) returns th

e smallest integer not less than x double exp (double x) returns ex

double fabs (double x) returns the absolute value of x

double floor (double x) returns the largest integer not greater than x

double log (double x) returns th e natural logarithm of x

double log10 (double x) returns the base 10 logarithm of x

Page 21: Pointers Variables and Memory Address

21

Some Mathematical Library Functions Defined in math.h Function Purpose

double sin (double x) returns the sine of x (x is in radians)

double cos (double x) returns the cosine of x (x is in radians)

double tan (double x) returns the tangent of x (x is in radians)

double sqrt (double x) returns the square root of x

double pow (double x,double y) returns xy

Defined in stdlib.h int abs(int x) returns the

absolute value of x

Page 22: Pointers Variables and Memory Address

22

# < . > /*include stdio h def initions of , */ # *include <math.h> / def inition of sqrt*/ ( ) { , , _ , second_sqrt, sum_sqrt;

T TT TTTTT TTT TTT TTT TTTTTTT TTT TTTTTT /* *root. / printf("Enter the first number> "); scanf("%lf", &first); first_sqrt = sqrt(first); printf("The square root of the first number % .2 " , _); */ Get second number and display its *square root. / printf("Enter the second number> "); scanf("%lf", &second); second_sqrt = sqrt(second); printf("The square root of the second number is %.2f\n", second_sqrt); T TTTTTT TTT TTTTTT TTTT TT TTT TTT TT/* TT. * / sum_sqrt = sqrt(first + second); printf("The square root of the sum of th 2e two numbers is %. f\n", sum_sqrt); 0return ( );}

Page 23: Pointers Variables and Memory Address

23

Question? What is the output of the

following code? int k, l, m;

f loat x = 2 5 .0 , y;T T TTTTTTTT

k = y; l = x – k;

m = sqrt(3 );printf(“y=%f,k=%d,l=%d,m=T TTTTTTTTTT TT

y=5.0, k=5, l=20, m=1

Page 24: Pointers Variables and Memory Address

24

จงเขยนโปแกรมเพอแกสมก�รห�ค� x ททำ�ใหค�f(x) = 0 เมอกำ�หนดสมก�รใหดงน

f(x) = 3x + sin(x) – ex

ใหใชวธก�รของนวตนในก�รแกสมก�รซงมสตรดงน

โดยมเงอนไขในก�รหยดก�รคำ�นวณเมอค�สมบรณของ | x1 - x0 | < 0.00001 แตถ�เงอนไขนไมจรงใหแทนค� x0 ดวย x1 แลวคำ�นวณใหมไปเรอยๆจนกว�เงอนไขทกำ�หนดไวเปนจรง จะได x1 เปนคำ�ตอบ

)0(')0(01

xfxfxx

Page 25: Pointers Variables and Memory Address

25

- User defined Functions• Takes data (called arguments)

• Can take as many arguments as needed

• Returns data (called returntype)

• Can only return one piece of data

Page 26: Pointers Variables and Memory Address

26

Function Definition• Syntax:

return_typefname(input_arguments)

{ local variable

declarations executable statements

}

Page 27: Pointers Variables and Memory Address

27

Example: Power2 function /* Finds the square of its

*input argument / double power2 (double

inp){

double out; *out = inp inp;

TTTTTT TTTT}

Page 28: Pointers Variables and Memory Address

28

Functions Without Arguments & Return

Value• Syntax:

void fname(void){

local variabledeclarations

executable statements}

Page 29: Pointers Variables and Memory Address

29

Example: Function declaration and

definition in a program A function named example

2that takes input arguments, and returns no data, would loo

k like: void example(double, int); int main(){ int b; . . . 52example( . , b) . . .} void example(double a, int b){ . . .}

Page 30: Pointers Variables and Memory Address

30

Declaring and Defining aFunction• TTT TTTTTTTT T TTTT-TTTTTTT

function, we need: 1 . Function declaration

(prototype), 2 . Function definition

(implementation)

Page 31: Pointers Variables and Memory Address

31

Function Declarations• Function declarationformat - -return value type - function name ( arguments ’ type );

• - - Return value type: data type of the result

(default i nt ) void T TTTTTTTTT TTTT TTT

function returns nothing• - Function name: any valididentifier• Arguments’ type: comma

separated list of arguments’ type

Page 32: Pointers Variables and Memory Address

32

Function DeclarationExample• TTT TT T TTTTTTTT TTT TT

my_function takes two - double type arguments

-and one int type argument, and returns a

- double type, the function declaration would be:

doubl e my_function(double,

double, int);

• - Each user defined function needs to be declared• All function declarations appear between• The preprocessor

directives, and• T he main function

Page 33: Pointers Variables and Memory Address

33

Example: Right Triangle TTTTTTT TTTT TTTTTTTTTT TTTTTTTTTT TT T TTTT/*

t triangle * / # < . > /*include stdio h because we are using p

rintf, scanf * / # *include <math.h> / because we are using s

*qrt in program / double calculate_hypotenuse(double, double);

( ){ double side1 , side2 , hypotenuse;

printf(“Please provide length of the first side :”);scanf(“%l ” , &1 ); printf(“\n Please provide length of the second sid

:”);scanf(“%l 2f”, &side ); hypotenuse = calculate_hypotenuse(side1 , sid

2e ); printf(“\n Hypotenuse = %f \n”, hypotenuse);

return 0 ;} double calculate_hypotenuse(double inp1, doubl

2e inp ){ doubleout ;

1* 1 2* 2out=sqrt(inp inp +inp inp ); returnout ;}

Page 34: Pointers Variables and Memory Address

34

- Top Down Design( divide and conquer)• -A problem solving method in which you f irst break a problem into its

major subproblems.• Then solve the

subproblems to derive the solution TT TTT TTTTTTTT TTTTTTT T• Subproblems areTTTTTTTTT TTTTTT TT TTT TT functions.

Page 35: Pointers Variables and Memory Address

35

* */ Draws a stick f igure / #include <stdio.h>

* */ function declarations (prototypes) / void draw_circle(void); */ Draws

*acircle/ void draw_intersect(void);

* */ Draws intersecting lines / void draw_base(void);

* */ Draws a base line / void draw_triangle(void);

* */ Draws a triangle / int main(void)

{ * */ Draw a circle. /

draw_circle(); * */ Draw a triangle. /

draw_triangle(); * */ Draw intersecting lines. /

draw_intersect(); 0return ( );

}

Page 36: Pointers Variables and Memory Address

36

* */ Draws a circle / void draw_circle(void){ printf(" * \n"); printf(“ * *\n"); printf(" * * \n");} * */ Draws a base line /

void draw_base(void){ --------- printf(“ \n");} * */ Draws a intersecting lines / void draw_intersect(void){

printf(" / \\ \n"); printf(“ / \\ \n"); printf(“/ \\ \n");} * */ Draws a triangle /

void draw_triangle(void){draw_intersect();draw_base();}

Page 37: Pointers Variables and Memory Address

37

ฟงกชน (Function)ฟงกชน คอ สวนของโปรแกรมทมลกษณะก�รทำ�ง�น

แบบโปรแกรมยอย (Subprogram) ซงบ�งฟงกชนผเขยนโปรแกรมส�ม�รถเรยกม�ใชง�นไดเพร�ะเปนฟงกชนม�ตรฐ�น

ทมม�กบภ�ษ�คอมพวเตอร สำ�หรบในภ�ษ�C จะแบงฟงกชน ออกเปน 2 ชนด คอ

1. Library Function หรอStandard Function2. ฟงกชนทผเขยนโปรแกรมกำ�หนดขนเอง 1. Library Function จะเปนฟงกชนม�ตรฐ�นทม�พรอมกบ ภ�ษ� C เกบไวในสวน Library ผเขยนโปรแกรมส�ม�รถเรยกใช

ได โดยใชคำ�สง #include แฟมขอมล ของฟงกชนนน ดงน#include <file_name>

Page 38: Pointers Variables and Memory Address

38

ตอไปนจะกล�วถงฟงกชนม�ตรฐ�นท ควรทร�บ คอ ฟงกชนคณตศาสตร(Mathematic Function)

ฟงกชนคณตศ�สตรจะอยในแฟมขอมล math.h จงตอง ระบ #include <math.h> ในตอนตนของโปรแกรมซงจะม

ฟงกชนต�งๆ ในก�รคำ�นวณท�ง คณตศ�สตร ตวแปรทใชใน ฟงกชนจะตองเปนชนดเลขจำ�นวนจรงdouble ผลลพธจะเปน

เลขจำ�นวนขรง doubleฟงกชนท�งคณตศ�สตรทใชในโปรแกรมมดงนsin(x) ใชห�ค� sine ของ x โดย x จะตองเปนมมใน

หนวยเรเดยนcos(x) ใชห�ค� cosine ของ x โดย x จะตองเปนมม

ในหนวยเรเดยน

Page 39: Pointers Variables and Memory Address

39

tan(x) ใชห�ค� tangent ของ x โดย x จะตองเปนมม ในหนวยเรเดยน

TTTT(x) ใชห�ค�มมในหนวย เรเดยนของค� sine ของ xacos(x) ใชห�ค�มมในหนวย เรเดยนของค� cosine

ของ xat an(x) ใชห�ค�มมในหนวย เรเดยนของค� tangent

ของ xsinh(x) ใชห�ค� hyperbolic sine ของ x cosh(x) ใชห�ค� hyperbolic cosine ของ xtanh(x) ใชห�ค� hyperbolic tangent ของ x

Page 40: Pointers Variables and Memory Address

40

sqrt(x) ใชห�ค�ร�กทสองของ x pow(x,y) ใชห�ค�ของ x ยกกำ�ลง y (xy)log(x) ใชห�ค� natural logarithm ของ x (logex)log10(x) ใชห�ค� log ฐ�น 10 ของ xexp(x) ใชห�ค� e ยกกำ�ลง x (ex)(e = 2.718282)fabs(x) ใชห�ค�สมบรณของ x ( absolute value) |x|ceil(x) ใชห�ค�เลขจำ�นวนเตมทมค�ม�กกว�หรอ

เท�กบค� xfloor(x) ใชห�ค�เลขจำ�นวนเตมทมค�นอยกว�หรอ

เท�กบค� x

Page 41: Pointers Variables and Memory Address

41

ฟงกชนเกยวกบสตรงก (String Function) ฟงกชนเกยวกบ string จะอยในแฟม ขอมล string.h จง

ตองระบ #include <string.h> ในตอนตนของโปรแกรมซงจะม ฟงกชนต�งๆ ดงน คอ

strcpy (str1 , str2) ใชในก�ร copy ค� str2 ไปยง str1

ตวอย�ง strcpy(str1,”Kmutt”);strcat(str1 , str2)

ใชในก�รเชอมตอ str1 และ str2 ผลลพธ จะถกเกบไวใน str1 ดง นน str1 จะตองมขน�ดใหญพอทจะเกบผล รวมของ string ทง 2

Page 42: Pointers Variables and Memory Address

42

strlen(str) ใชห�ค�คว�มย�วของ string

strcmp(str1 , str2) ใชในก�รเปรยบเทยบ str1 และ str2 โดยใช ค� ASCII เปนหลก

ผลของก�รเปรยบเทยบจะเปนดงน ถ� str1 < str2 จะไดผลลพธนอยกว�ศนย ถ� str1 = str2 จะไดผลลพธเปนศนย ถ� str1 > str2 จะไดผลลพธม�กกว�ศนย

Page 43: Pointers Variables and Memory Address

43

String Comparison strcmp(“thrill”, “throw”);

returns a negative integer strcmp(“read”, “readable”);

returns a negative integer strcmp(“shrimp”, “crab”);

returns a positive integer strcmp(“end”, “end”);

returns zero strncmp:Prototype: int strncmp(char *s1, char*s2, unsignedn);

Purpose: Compares the first n characters of s1 and s2 returning

positive, zero, and negative values a s does strcmp.

Example: strncmp(“read”, “readable”, 1);

strncmp(“read”, “readable”,2 );

strncmp(“read”, “readable”,3); All returns zero

strncmp(“read”, “readable”, 4 );

Page 44: Pointers Variables and Memory Address

44

ฟงกชนเกยวกบตวอกษรฟงกชนเกยวกบตวอกษรจะอยในแฟม ขอมล ctype.h จง

ตองระบ #include <ctype.h> ในตอนตนของโปรแกรมซงจะม ฟงกชนต�งๆ ดงน คอ

tolower(ch) ใชในก�รเปลยนตวอกษรจ�กตวใหญเปนตวเลก

toupper(ch) ใชในก�รเปลยนตวอกษรจ�กตวเลกเปนตว ใหญ

isalnum(ch) จะใหค�เลขจำ�นวน เตมซงไมเท�กบศนย ถ� ch มค�เปนตวอกษร หรอตวเลข และ จะให ค�เปนศนย ถ� ch ไมไดมค�เปนตวอกษร หรอตวเลข

Page 45: Pointers Variables and Memory Address

45

isalpha(ch) จะใหค�เลขจำ�นวนเตมซงไมเท�กบศนย ถ�ch มค�เปนตวอกษร

และ จะใหค�เปนศนย ถ� ch ไมไดมค�เปนตวอกษรรวมถงเครองหม�ยต�งๆ

isdigit(ch) จะใหค�เลขจำ�นวนเตมซงไมเท�กบศนย ถ�ch มค�เปนตวเลข

- 0 9 และ จะใหค�เปนศนย ถ� ch ไมไดมค�เปนตวเลขislower(ch)

จะใหค�เลขจำ�นวนเตมซงไมเท�กบศนย ถ�ch มค�เปนตวอกษร ตวเลกและ จะใหค�เปนศนย ถ� ch เปนตวอกษรอนๆ

isupper(ch) จะใหค�เลขจำ�นวนเตมซงไมเท�กบศนย ถ�ch มค�เปนตวอกษร

ตวใหญและ จะใหค�เปนศนย ถ� ch เปนตวอกษรอนๆ

Page 46: Pointers Variables and Memory Address

46

ispunct(ch) จะใหค�เลขจำ�นวนเตมซงไมเท�กบศนย ถ�ch มค�เปน

เครองหม�ยวรรคตอนและ จะใหค�เปนศนย ถ� ch ไมเปนเครองหม�ยวรรคตอน

isxdigit(ch) จะใหค�เลขจำ�นวนเตมซงไมเท�กบศนย ถ�ch มค�เปนตวเลข

ในระบบเลขฐ�นสบหกไดแก - 0 9 , A-F หรอ a-f และ จะใหค� เปนศนย ถ� ch เปนตวอกษรอนๆ

isprint(ch)iscntrl(ch)isgraph(ch)isspace(ch)

Page 47: Pointers Variables and Memory Address

47

ฟงกชนอนๆ ทวไป ฟงกชนอนๆ นอกจ�กทกล�วม�แลว จะอยในแฟมขอมล

stdlib.h จงตองระบ #include <stdlib.h> ในตอนตนของ โปรแกรมซงจะมฟงกชนต�งๆ ดงน คอ

abs(x) ใชห�ค�สมบรณของ T ซงเปนเลขจำ�นวนเตมl abs(x) ใชห�ค�สมบรณของ T ซงเปนเลขจำ�นวนเตม

ย�วabort() ใชในก�รยกเลกก�รทำ�ง�นของโปรแกรม

ขณะนน และมขอคว�มAbnormal program termination ปร�กฏบนจอภ�พ

Page 48: Pointers Variables and Memory Address

48

ฟงกชนอนๆ ทวไป(ตอ)atof(str) ทำ�หน�ทเปลยน string เปนขอมลเลขทศนยม

ละเอยดสองเท�atoi(str) ทำ�หน�ทเปลยน string เปนขอมลเลขจำ�นวน

เตมatol(str) ทำ�หน�ทเปลยน string เปนขอมลเลขจำ�นวน

เตมย�วclrscr() ใชในก�ร clear จอภ�พใหว�งclreol() ใชลบขอคว�มในบรรทดทcursor อยไปจนจบ

บรรทดนน

Page 49: Pointers Variables and Memory Address

49

Converting a String Into an i nt Using atoi

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

int main(){

1char str [] =1243 87" z yu ";

-2 34char str [] = " . "; * 3 24char str = "e ";

1 1printf("str : %d\n", atoi(str )); 2 2printf("str : %d\n", atoi(str )); 3 3printf("str : %d\n", atoi(str ));

0return ;}

Output:

1str :124

-2 : 3str 30str :

Page 50: Pointers Variables and Memory Address

50

ฟงกชนอนๆ ทวไป(ตอ)gotoxy(x , y)

ใชสำ�หรบก�รเลอน cursor ไปยงตำ�แหนงทตองก�รบนจอภ�พ โดยท x เปนตำ�แหนงคอลมน และ y เปนตำ�แหนงบรรทด

exit(status) ใชยกเลกก�รทำ�ง�นของโปรแกรมขณะนน ค� status ปกตจะม

ค�เปนศนยถ�เปนก�รจบโปรแกรมต�มปกต สวนกรณอนๆ จะเปนก�รใชแทนขอผดพล�ดต�งๆ

delline() ใชลบบรรทดท cursor อยแลวเลอนบรรทดทอยข�งล�งขนม�

แทนท

Page 51: Pointers Variables and Memory Address

51

ฟงกชนอนๆ ทวไป(ตอ)insline() ใชแทรกบรรทดว�งลงไป ใตบรรทดท cursor

อยอก 1 บรรทดsizeof(x) ใชตรวจสอบขน�ดของตวแปรว�มขน�ดก

ไบทsystem(“command”) ใหผเขยนโปรแกรมส�ม�รถใช

คำ�สงในMS-DOS ไดขณะทอย ในภ�ษ� C ตวอย�ง

system(“dir”);

Page 52: Pointers Variables and Memory Address

52

2. ฟงกชนทผเขยนโปรแกรมกำาหนดขนเอง นอกจ�กฟงกชนม�ตรฐ�นในภ�ษ� C ทไดกล�วไปแลว

นน ผเขยนโปรแกรมส�ม�รถกำ�หนดฟงกชนขนม�ใชง�นได เองต�มวตถประสงคของผเขยนโปรแกรมลกษณะก�รทำ�ง�น

ของฟงกชนจะมก�รสงค�หรอรบค�ระหว�ง โปรแกรมหลก( main) กบฟงกชนทสร�งขน รปแบบก�รกำ�หนดฟงกชน

function type function_name (data_type var…){ …

…statement;…

return (value);}

Page 53: Pointers Variables and Memory Address

53

ก�รเรยกใชฟงกชนทกำ�หนดขนเองมรปแบบดงนfunction_name (arg1 , arg2 , arg3 , … , argn)

ลกษณะก�รเขยนโปรแกรมหลก main( ) และ ฟงกชนmain( ){ ...statement;… function_name( );…} function_name( ){ …statement;… return ( );}

Page 54: Pointers Variables and Memory Address

54

ตวแปร Local และตวแปร Global ตวแปร Local เปนตวแปรทกำ�หนดขน ภ�ยใน block

( เครองหม�ย { } ) ของฟงกชน ซงตแปรLocal จะมผลเฉพ�ะในฟงกชนนนๆ

ตวแปร Global เปนตวแปรทใชรวมกนไดทกฟงกชนใน โปรแกรมเดยวกน โดยจะถกเขยนไวนอกฟงกชนใดๆ

#include <stdio.h>int a,b,c;float x,y,z;main( ){int m,n;float f,h;

Global variables

Local variables

Page 55: Pointers Variables and Memory Address

55

LOCAL VARIABLES• Each function has its own

local variables.• T TTTTTTT TTTTTTTTT

(including main()) can have the local variables with

the same name.• Although they may have

same name, they are TTT TTT TTT T TTTTTTTTT

Page 56: Pointers Variables and Memory Address

56

EXAMPLE: LOCAL VARIABLE #include <stdio.h>

(); ( ){ = 1; (“ % ” , ) ;(); printf(“main local variable x is still %d”,x); return 0;} void myfunc(void){ int x;2x= ; printf(“ myfunc local variable x is %d”,x);}

Page 57: Pointers Variables and Memory Address

57

วธการเขยนโปรแกรมแบบ Recursion (การเรยกซำา)เปนวธก�รเขยนฟงกชนขนม�ใชเองและภ�ยในฟงกชน

นนมก�รเรยกใชฟงกชนนนซำ�ภ�ยในตวของ มนเอง สงทจะ ตองกำ�หนดขนภ�ยในฟงกชนเมอเขยนแบบrecursion คอ

1. Base cases2. Making progress

ตวอย�งfac(int x){ if(x == 0) return 1; else return (x*fac(x-1));

Page 58: Pointers Variables and Memory Address

58

Preprocessor เปนก�รนำ�เอ�คำ�สงอนๆ ม�รวมเข�กบโปรแกรมทผเขยน

โปรแกรมเขยนขนเอง กอนทำ�ก�รcompile โปรแกรม ก�รเขยนคำ�สง preprocessor จะม เครองหม�ย # นำ�หน�

และจบคำ�สงโดยไมตองมเครองหม�ย ; ใน preprocessor จะประกอบดวยpreprocessor

directive อยจำ�นวนม�ก ซงจะแนะนำ�บ�งตวใหทร�บดงน# define

ใชกำ�หนดค�ขอมลใหกบชอแมคโคร(macro_name) ท ตงขน ถ�มก�รเรยกใชชอแมคโครนน กจะม ค�ต�มทกำ�หนด ม

รปแบบคำ�สงดงน#define macro_name string

Page 59: Pointers Variables and Memory Address

59

ชอแมคโคร (macro_name) อ�จจะเขยนดวยอกษรตว ใหญหรอตวเลกกได แตทนยนมเขยนดวยตวอกษรตวใหญ

Defined constants (#define)You can define your own names for constants that youuse very often without having to resort to memory-consuming variables, simply by using the #preprocessor directive . Its format is:

#define identifier valueFor example :

#define PI 3.14159265#define NEWLINE '\n' #define ABC(a,b,c) (a>b && a>c) ? 1:0

Page 60: Pointers Variables and Memory Address

60

Conditional operator ( ? )The conditional operator evaluates an expression returning a value if that expression is true and a different one if the expression is evaluated as false . Its format is :condition ? result1 :result2If TTTTTTTTT is true the expression will return result1, if it is not it will return 2result .7TT5 ? 4 : 3 TTTTTTT T T 3

7 5since is not equal to . 7TT5+2 ? 4 : 3 4 7// returns , since is equal 5 2to + . 5>3 ? a : b TT TTTTTTT TTT value of a, since 5 is greater 3than. a>b ? a : b TT TTTTTTT whichever is greater, a or b.

Page 61: Pointers Variables and Memory Address

61

#include ใชบอกใหตวแปลภ�ษ� (compiler) นำ�แฟมขอมลอนม�

ใชรวมกบคำ�สงทอยภ�ยในโปรแกรมทเขยนขนเองมรปแบบคำ�สงดงน

#include “file_name”หรอ #include <file_name>

Page 62: Pointers Variables and Memory Address

62

คำาสง switch( )ก�รเขยนโปรแกรมทประกอบดวยหล�ยเงอนไขส�ม�รถ

ใชคำ�สง switch() ได ดงรปแบบคำ�สงตอไปน switch (v) {case constant1 :statement;break;case constant2 :statement;break;..default :statement;}

Page 63: Pointers Variables and Memory Address

63

switch Statement• To select one of several alternatives.• Selection is based on the

value of an expression.• Expression could be a singlevalue.• The type of expression can

be either int or char type, but not double.

Page 64: Pointers Variables and Memory Address

64

switch StatementSyntax: switch (expression){ -case const expr: statements; break; -case const expr: statements; break; . -case const expr: statements; break; default: statements; break; }

Page 65: Pointers Variables and Memory Address

65

#include <conio.h>#include <stdio.h>void main(){char code; clrscr(); printf("input ship code : "); scanf("%c",&code); switch (code) { case 'B' : case 'b' : printf("Battership\n"); break; case 'C' : case 'c' : printf("Cruiser\n"); break; case 'D' : case 'd' : printf("Destroyer\n"); break; case 'F' : case 'f' : printf("Frigate\n"); break; default : printf("Unknown ship calss %c\n",code); }}input ship code : fFrigate

Page 66: Pointers Variables and Memory Address

66

#include <conio.h>#include <stdio.h>void main(){char sw;float a,b,c; clrscr(); printf("input expresion : "); scanf("%f%c%f",&a,&sw,&b); switch (sw) { case '+' : c = a + b; break; case '-' : c = a - b; break; case '*' : c = a * b; break; case '/' : c = a / b; break; } printf("output c = %f",c);}input expression : 1.5*1.5output c = 2.250000

Page 67: Pointers Variables and Memory Address

67

ขอมลชนดโครงสราง(Structure) เปนก�รรวมกลมของตวแปรเข�ดวยกนภ�ยใตชอโครง

สร�งเดยวกน โดยมรปแบบดงน

struct structure_name {type var_name-1;

-2type var_name ;..

type -var_name n; } sturcture_var;

Page 68: Pointers Variables and Memory Address

68

ตวอย�งstruct student_data {TTT TTT

char name[40]; char address[50];

TTT TTTT } student;

ก�รอ�งถงตวแปรทอยในโครงสร�ง มรปแบบดงนstructure_var.var_name

เชน student.name

Page 69: Pointers Variables and Memory Address

69

ก�รกำ�หนดตวแปรใหมโครงสร�งเหมอนกบกลมโครงสร�งท มอยแลว มรปแบบดงน

struct structure_name structure_var;

เชนstruct student_data chem,math;

Page 70: Pointers Variables and Memory Address

70

ขอมลแบบยเนยน(union)เปนขอมลชนดหนงคล�ยกบขอมลแบบ โครงสร�ง โดย

สม�ชกทกตวจะใชหนวยคว�มจำ�เดยวกนโดยมรปแบบดงน

TTTTT union_name {type var_name-1;

-2type var_name ;..

type -var_name n; } union_var;

Page 71: Pointers Variables and Memory Address

71

ตวอย�งTTTTT data_ab {

TTT TT char b;

} var_ab; ก�รกำ�หนดค�หรออ�งถงขอมลใน union

var_ab.a = 25;ab

Page 72: Pointers Variables and Memory Address

72

การเปดแฟมขอมล (File)ก�รเปดแฟมขอมลมรปแบบดงนFILE *fpfp = fopen(f_name,mode);

fp เปน file pointer ของขอมลแบบ โครงสร�งชนด FILEfopen เปนฟงกชนทใชในก�รเปดแฟมขอมลf_name เปนชอแฟมขอมลmode เปน status ของก�รเปดแฟมขอมล

“r” เปดไฟลเพอก�รอ�นขอมล“w” สร�งไฟลใหมเพอบนทกขอมล“a” เปดไฟลเพอเพมขอมลตอท�ยไฟล

Page 73: Pointers Variables and Memory Address

73

รปแบบขอมลกำาหนดได 2 แบบt บนทกขอมลแบบขอคว�ม Textb บนทกขอมลแบบเลขฐ�นสองBinary

การปดแฟมขอมล fclose(fp);

ฟงกชน fprintf() และ fscanf() เปนก�รเขยนและอ�นขอมลกบไฟล มรปแบบดงน

fprintf(fp,control_string,var_list);fscanf(fp,control_string,var_list);

Page 74: Pointers Variables and Memory Address

74

#include <stdio.h>#include <conio.h>T TTTTT{TTT TT

*FILE mathf ile;T TTTTTTT T fopen(“a:test.txt”,”wt”);clrscr()for(i=1;i<=20;i++) fprintf(mathfile,”%d\n”,i);fclose(mathfile);}

Page 75: Pointers Variables and Memory Address

75

#include <stdio.h>#include <conio.h>main(){ i nt i,a; FILE * mathf ile;

T TTTTTTT T fopen(“a:test.txt”,”Tt”);clrscr()for(i=1;i<=5 TTTTT{ f scanf(mathfile,”%d”,&a); printf(“a[%d] = %d\n”,i,a);}fclose(mathfile);}

Page 76: Pointers Variables and Memory Address

76

#include <conio.h>#include <stdio.h>void main(){int i,j,id,price;char name[20],author[20]; FILE *stfile; stfile = fopen("book.dat","wt"); for(i=1;;i++) { clrscr(); gotoxy(20T5);printf("record no # %d",i); gotoxy(20T6 );printf("book id :"); gotoxy(20T7 ;printf("book name :"); gotoxy(20T8);printf("author :"); gotoxy(20T9 );printf("price :"); gotoxy(32T6);scanf("%d",&id); if(id==0)break;

Page 77: Pointers Variables and Memory Address

77

gotoxy(32T7);scanf("%s",&name); gotoxy(32T8);scanf("%s",&author); gotoxy(32T9);scanf("%d",&price); fprintf(stfile,"%d %s %s %d\n",id,name,author,price); } fclose(stfile);}

Page 78: Pointers Variables and Memory Address

78

#include <conio.h>#include <stdio.h>void main(){int i,j,id,price;char name[20],author[20]; FILE *stfile; stfile = fopen("book.dat","rt"); clrscr(); printf("No. Book_id NAME "); printf("AUTHOR PRICE\n"); for(i=1 ;;i++) { fscanf(stfile,"%d%s%s%d",&id,&name,&author,&price); if(feof(stfile)!=0 break; printf("%-5 d%-10d%-20s%-20s%d\n",i,id,name,author,price); } fclose(stfile);}

Page 79: Pointers Variables and Memory Address

79

ในก�รใชฟงกชน fopen( ) จะใหค� NULL ถ�ไมส�ม�รถเปดFile ไดตวอย�ง#include <stdio.h>main( ){FILE *fp;If((fp=fopen(“math.dat”,”w”))==NULL) {

printf(“cannot open file\n”);return 0;

Page 80: Pointers Variables and Memory Address

80

ฟงกชน fputs() และ fgets()เปนก�รเขยนและอ�นขอมล string กบ ไฟล มรปแบบดงน

fputs(str , fp);fgets(str , num , fp);

Page 81: Pointers Variables and Memory Address

81

#include <conio.h>#include <stdio.h>#include <string.h>void main(){int i,j;char name[20],author[20],sp[1],id[5],price[7];FILE *stfile; stfile = fopen("book4.dat","wt"); for(i=1;;i++) { clrscr(); gotoxy(20T5);printf("record no # %d",i); gotoxy(20T6);printf("book id :"); gotoxy(20T7);printf("book name :"); gotoxy(20T8);printf("author :"); gotoxy(20T9);printf("price :"); gotoxy(32T6);gets(id); if(id[0]=='\0')break;

Page 82: Pointers Variables and Memory Address

82

gotoxy(32T7);gets(name); gotoxy(32T8);gets(author); gotoxy(32T9);gets(price); strcat(id,"\n"); fputs(id,stfile); strcat(name,"\n"); fputs(name,stfile); strcat(author,"\n"); fputs(author,stfile); strcat(price,"\n"); fputs(price,stfile); } fclose(stfile);}

Page 83: Pointers Variables and Memory Address

83

#include <conio.h>#include <stdio.h>#include <stdlib.h>void del(char a[20]);void main(){int i,j,i_id,i_price;char name[20],author[20],id[5 ] ,price[7 ] ; FILE *bfile; bfile = fopen("book4.dat","rt"); FILE *bfile2 ; bfile T 2fopen("report.dat","wt"); clrscr(); fprintf(bfile2 ,"No. Book_id NAME "); fprintf(bfile2 ,"AUTHOR PRICE\n"); for(i=1 ;;i++) { fgets(id,5 ,bfile); fgets(name,20,bfile);

Page 84: Pointers Variables and Memory Address

84

fgets(author,20,bfile); fgets(price,7 ,bfile); if(feof(bfile)!=0)break; i_id = atoi(id); i_price = atoi(price); del(name); del(author); fprintf(bfile2 ,"%-4 d%-9 d%-20s",i,i_id,name); fprintf(bfile2 ,"%-20s%d\n",author,i_price); } fclose(bfile); fclose(bfile2);}void del(char a[20]){int i; for(i=0 ;i<20;i++) if(a[i]=='\n')break; a[i] = '\0 ';}

Page 85: Pointers Variables and Memory Address

85

ฟงกชน fwrite() และ fread() ในการสราง file แบบ record เปนก�รเขยนและอ�นขอมลกบไฟล มรปแบบดงน

fwrite(pt , bytes , n , fp);fread(pt , bytes , n , fp);

pt เปน pointer ของตวแปรbytes เปนขน�ดของตวแปรn เปนจำ�นวนขอมลfp เปน file pointer

Page 86: Pointers Variables and Memory Address

86

#include <conio.h>#include <stdio.h>#include <string.h>struct data { int id; char name[20]; char author[20]; int price;}book;void main(){int i,j;char sp[1]; FILE *stfile; stfile = fopen("book3.dat","wb"); for(i=1;;i++) { clrscr(); gotoxy(20T5);printf("record no # %d",i); gotoxy(20T6);printf("book id :"); gotoxy(20T7);printf("book name :"); gotoxy(20T8);printf("author :");

Page 87: Pointers Variables and Memory Address

87

gotoxy(20T9);printf("price :"); gotoxy(32T6);scanf("%d",&book.id); if(book.id==0)break; gets(sp); gotoxy(32T7);gets(book.name); gotoxy(32T8);gets(book.author); gotoxy(32T9);scanf("%d",&book.price); fwrite(&book,sizeof book,1,stfile); } fclose(stfile);}

Page 88: Pointers Variables and Memory Address

88

#include <conio.h>#include <stdio.h>struct data { int id; char name[20]; char author[20]; int price;}book;void main(){int i,j; FILE *stfile; stfile = fopen("book3.dat","rb"); clrscr(); printf("No. Book_id NAME "); printf("AUTHOR PRICE\n");

Page 89: Pointers Variables and Memory Address

89

for(i=1;;i++) { fread(&book,sizeof book,1,stfile); if(feof(stfile)!=0)break; printf("%-4 d%-9 d%-20s",i,book.id,book.name); printf("%-20s %d\n",book.author,book.price); } fclose(stfile);}