Pointers Variables and Memory Address When a variable (of type int, double, char, etc.) is declared in a C program code, the operating.

Download Report

Transcript Pointers Variables and Memory Address When a variable (of type int, double, char, etc.) is declared in a C program code, the operating.

Pointers
Variables
Address and Memory
When
a variable
(of type int, double,
char, etc.)
is declared
in
a C program
the operating
system
allocatescode,
a location
for
the variable
somewhere
memory.
The value
of the in the
variable is stored at this location.
int num = 0;
of the variable num
0 1000
num
1004
1006
1008
1010
1002 The address
An
address
(e.g. 1002),
variable,
identifies
the assigned to the
memory
location
of thatisvariable. 1
Every time
the variable
Variables
and
Memory
Address
So
far, we have
not
been
concerned
about
memory
addresses.
However,
language
offers a powerful
toolCto
access
and
manipulate
the
addresses of variables by means
of pointers.
The & (address of) operator
Recall the use of the scanf function:
scanf(“%d”,&num);
The
& operator,
evaluates
the 2
address
of the variable
num.
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
3
Pointers
int num;
1000
nu
0
num = 0;
m
1002
pointer int *ptr_num;ptr_n 10
1004
um
02
declaration ptr_num = #
1006
1008
1010
• ptr_num is declared as a pointer
to an integer variable.
/
• then, it is assigned
the address
4
of the integer variable
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_num
ptr_num
ptr_n
nu
0
ptr_num
is
a
pointer
to the
um
m
integer variable
num:
/
5
Pointer Types
Pointers can be declared to
point to variables of any
type.
•
Examples:
int *ptr_num1; (pointer to an
integer or integer
pointer).
double *ptr_num2;
(pointer to
a floating point
6
Example Program
#include <stdio.h>
int main ( ){
nu
1002
nu
int num1, num2, product;m1
prod
m2
1004
uct
int *ptr_num1, *ptr_num2;
1006
ptr_n
num1 = 5;
ptr_n
um1
1008
um2
num2 = 7;
1010
ptr_num1 = &num1;
1012
ptr_num2 = &num2;
1014
product = num1*( *ptr_num2 );
7
printf(“The address of num1 is %p\n”,
Brain Exercise on Pointers
What is the output of the
following code segment?
#include<stdio.h>
void main() {
int x[5] = {0, 1, 2, 3, 4};
int *yptr, i;
yptr = &x[1];
for ( i=0; i<3; i++)
yptr[ i ] = -1;
for (i=0; i<5; i++)
printf(“%d ”, x[i]);
}
8
Exercise
#include <stdio.h>
void main()
{
double x[4] = {1.0, 2.0, 3.0, 4.0};
double *xptr;
int k;
xptr = &x[2];
*(xptr+1) = -1.0;
for (k=0; k<4; k++)
printf(“%f ”, x[k]);
}
1.0 2.0 3.0 -1.0
9
พอยน์เตอร ์ (Pointer)
่
่
่
Pointer
คื
อ
ตั
ว
แปรชนิ
ด
หนึ
งที
ท
ำหน้
ำ
ที
่ ่
เก็บตำแหน่ งทีอยู
่
(address)
ของตั
ว
แปรแทนที
จะเก็
บ
ข
้อมู
ล
ต่ำงๆ
กำรกำหนดชนิ ดของตัวแปรพอยน์เตอร ์
่ ำหน้ำทีเป็
่ นตัวแปรพอยน์
ตั
ว
แปรที
จะท
เตอร ์จะต ้องมีกำร
ก
ำหนดไว
้ก่
อ
นตอนต
้นของโปรแกรมโดยมี
้
รูปแบบดังนี
type *var_name
type
- ชนิ ดของตัวแปร
่
่
*
เป็
นเครื
องหมำยที
แสดงว่
ำ
ตั
ว
แปร
่
ทีตำมหลัง
่
้ นตัวแปร Pointer
10
เครืองหมำยนี
เป็
่ ้ในตัวแปรพอยน์เตอร ์
่
ใช
เครืองหมำยที
่
่
่ ้
1.
เครื
องหมำย
&
เป็
นเครื
องหมำยที
ใช
สำหร ับให ้ค่ำ
่
่
ต
ำแหน่
ง
ที
อยู
่
(address)
ของตั
ว
แปรซึ
งอยู
่
่
หลังเครืองหมำย &
ตัวอย่ำง
int a = 5 , *b;
b = &a;
ค่ำในหน่ วยควำมจำ
a
b
ค่ำข ้อมูล
5
1000
address
1000
11
่ ้ในตัวแปรพอยน์เตอร ์ (ต่อ)
่
ใช
เครืองหมำยที
่
่
2.
เครื
องหมำย
*
จะให
้ค่
ำ
ของขั
อ
มู
ล
ซึ
ง
เก็บอยูใ่ น
่
่
ต
ำแหน่
ง
ที
อยู
่
(address)
ที
ตั
ว
แปร
Pointer
้
้
นันชีอยูอ
่ อกมำ
ตัวอย่ำง
int a , b , *c;
a = 10;
c = &a;
b = *c;
ค่ำในหน่ วยควำมจำ
a
c
b
ค่
ำ
ข
้อมู
ล
10
2000
10
12
่ ำหน้ำทีเป็
่ น Pointer
ตัวแปรพอยน์เตอร ์ทีท
เป็
นกำรก
ำหนดตั
ว
แปร
Pointer
ให
้
่
สำมำรถเก็บตำแหน่ งที
อยู
่
(address)
ของตั
ว
แปร
Pointer
อั
ก
ตั
ว
้
หนึ ง ลักษณะแบบนี อำจ
เรียกว่ำ Indirect pointer
ตัวแปร
pointer_1
pointer_2
กำรก
ำหนดตั
ว
แปร
pointer
ของ
pointer
มี
้
รูปแบบดังนี
type **pointer_var
13
ตัวอย่ำง
int a , *p_1 , **p_2;
int b;
a = 15;
p_1 = &a;
p_2 = &p_1;
b = **p_2;
a
p_1
15
1000
15
address 1000
2000
p_2
b
2000
3000
14
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
15
Function Calls
Format : FunctionName(
argument list );
Arguments may be
• constants
• variables
• expressions
Argument list consists of
16
Function Calls
• Functions may be called as a
part of assignment:
Example: y=sqrt(x);
Here sqrt is a predefined
function which takes the square
root of its argument. In the
above statement, the value
17
Functions: Classification
• We can classify functions into
two main groups:
• (Predefined) Library
Functions:
Example : printf
• User Defined Functions:
We’ll learn how to write our18
(Predefined) Library
Functions
• 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
19
at the top of the
Some Mathematical Library
Functions Defined in math.h
Function
Purpose
double ceil(double x)
returns the
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
20
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 21
#include <stdio.h> /* definitions of printf, scanf
*/
#include <math.h> /* definition of sqrt */
int main(void) {
double first, second, first_sqrt, second_sqrt,
sum_sqrt;
/* Get first number and display its square root.
*/
printf("Enter the first number> ");
scanf("%lf", &first);
first_sqrt = sqrt(first);
printf("The square root of the first number is
%.2f\n", first_sqrt);
/* 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);
/* Display the square root of the sum of the22two
Question?
What is the output of the
following code?
int k, l, m;
float x = 25.0, y;
y = sqrt(x);
k = y;
l = x – k;
m = sqrt(3);
printf(“y=%f,k=%d,l=%d,m=%d”,y
,k,l,m);
23
่
จงเขี
ย
นโปแกรมเพื
อแก
้สมกำรหำค่
ำ
x
่
ทีทำให ้ค่ำ
่ ำหนดสมกำรให ้ดังนี ้
f(x) = 0 เมือก
f(x) = 3x + sin(x) – ex
ให
้ใช
้วิ
ธ
ก
ี
ำรของนิ
ว
ตั
น
ในกำรแก
้
่
สมกำรซึงมีสต
ู ร
f ( x0)
้
ดังนี
x1  x0 
f ' ( x0)
่
โดยมี
เ
งื
อนไขในกำรหยุ
ด
กำรค
ำนวณ
่
เมือค่ำสัมบูรณ์
ของ
|
x1
x0
|
<
0.00001
แต่
ถ
้ำ
่
้
เงือนไขนี ไม่จริงให ้
24
แทนค่ำ x0 ด ้วย x1 แล ้วคำนวณใหม่
User - defined Functions
• Takes data (called arguments)
• Can take as many
arguments as needed
• Returns data (called return
type)
• Can only return one piece of
data
25
Function Definition
• Syntax:
return_type
fname(input_arguments)
{
local variable declarations
executable statements
}
26
Example: Power2 function
/* Finds the square of its input
argument */
double power2(double inp)
{
double out;
out = inp*inp;
return out;
27
Functions Without
Arguments & Return Value
• Syntax:
void fname(void)
{
local variable declarations
executable statements
}
28
Example: Function declaration
and definition in a program
A function named example that
takes 2 input arguments, and
returns no data, would look like:
void example(double, int);
int main()
{
int b;
...
example(5.2, b)
...
}
void example(double a, int b)
{
...
29
Declaring and Defining a
Function
• For creating a user-defined
function, we need:
1. Function declaration
(prototype),
2. Function definition
(implementation)
30
Function Declarations
• Function declaration format
return-value-type functionname ( arguments’ type );
• Return-value-type:
data type of the result
(default int)
void – indicates that the
function returns
nothing
31
Function Declaration Example
• So, if a function named
my_function takes two
double- type arguments and
one int-type
argument, and returns a
double-type, the function
declaration would be:
double
my_function(double, double,
int);
32
Example: Right Triangle
/* Program that calculates hypotenuse of a right
triangle */
#include <stdio.h> /* because we are using printf,
scanf */
#include <math.h> /* because we are using sqrt in
program */
double calculate_hypotenuse(double, double);
Int main()
{
double side1, side2, hypotenuse;
printf(“Please provide length of the first side :”);
scanf(“%lf”, &side1);
printf(“\n Please provide length of the second side:”);
scanf(“%lf”, &side2);
hypotenuse = calculate_hypotenuse(side1, side2);
printf(“\n Hypotenuse = %f \n”, hypotenuse);
return 0;
}
double calculate_hypotenuse(double inp1, double
inp2)
{
33
Top - Down Design (divide
and conquer)
• A problem-solving method
in which you first
break a problem into its
major subproblems.
• Then solve the subproblems
to derive the solution
34
/* Draws a stick figure */
#include <stdio.h>
/* function declarations (prototypes) */
void draw_circle(void);
/* Draws a circle */
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();
35
return (0);
/* 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();
}
36
ฟั งก ์ช ัน (Function)
่ ลก
ฟั
ง
ก
์ช
ัน
คื
อ
ส่
ว
นของโปรแกรมที
มี
ั
ษณะ
กำรทำงำน
่
แบบโปรแกรมย่
อ
ย
(Subprogram)
ซึ
งบำง
ฟังก ์ช ันผูเ้ ขียน
โปรแกรมสำมำรถเรี
ย
กมำใช
้งำนได
้เพรำะเป็
น
ฟังก ์ช ันมำตรฐำน
่ มำกับภำษำคอมพิวเตอร ์ สำหร ับในภำษำ C
ที
มี
จะแบ่งฟังก ์ช ัน
ออกเป็ น 2 ชนิ ด คือ
1.
Library
Function
หรื
อ
Standard
Function
่ เ้ ขียนโปรแกรมกำหนดขึน้
2.
ฟั
ง
ก
์ช
ันที
ผู
เอง
1.
Library
Function
จะเป็
นฟั
ง
ก
์ชัน
่
มำตรฐำนทีมำพร ้อมกับ
37
ภำษำ C เก็บไว ้ในส่วน Library ผูเ้ ขียน
้
่
ต่
อ
ไปนี
จะกล่
ำ
วถึ
ง
ฟั
ง
ก
์ช
ันมำตรฐำนที
ควร
ทรำบ คือ
ฟั
งก
์ช
ันคณิ
ต
ศาสตร
์
(Mathematic
Function)
ฟั
ง
ก
์ช
ันคณิ
ต
ศำสตร
์จะอยู
ใ
่
นแฟ้
มข
้อมู
ล
math.h จึงต ้อง
ระบุ
#include
<math.h>
ในตอนต
้นของ
่
โปรแกรมซึงจะมี
ฟั
ง
ก
์ช
ันต่
ำ
งๆ
ในกำรค
ำนวณทำงคณิ
ต
ศำสตร
์
่
ตัวแปรทีใช ้ใน
ฟั
ง
ก
์ช
ันจะต
้องเป็
นชนิ
ด
เลขจ
ำนวนจริ
ง
double ผลลัพธ ์จะเป็ น
เลขจำนวนขริง double
่
ฟั
ง
ก
์ช
ันทำงคณิ
ต
ศำสตร
์ที
ใช
้ในโปรแกรม
้
มีดงั นี
sin(x)
ใช
้หำค่
ำ
sine
ของ
x
โดย
x
จะต ้องเป็ นมุมใน
38
tan(x)
ใช
้หำค่
ำ
tangent
ของ
x
โดย x จะต ้องเป็ นมุม
ในหน่ วยเรเดียน
asin(x)
ใช
้หำค่
ำ
มุ
ม
ในหน่
ว
ยเรเดี
ย
นข
องค่ำ sine ของ x
acos(x)
ใช
้หำค่
ำ
มุ
ม
ในหน่
ว
ยเรเดี
ย
นข
องค่ำ cosine
ของ x
atan(x)
ใช
้หำค่
ำ
มุ
ม
ในหน่
ว
ยเรเดี
ย
นข
องค่ำ tangent
ของ x
sinh(x)
ใช
้หำค่
ำ
hyperbolic
sine
ของ x
cosh(x)
ใช
้หำค่
ำ
hyperbolic
cosine ของ x
39
tanh(x)
ใช ้หำค่ำ hyperbolic
่
sqrt(x)
ใช ้หำค่ำรำกทีสองของ
x
pow(x,y)
ใช
้หำค่
ำ
ของ
x
ยกก
ำลั
ง
y
y (x )
log(x)
ใช
้หำค่
ำ
natural
logarithm ของ x (logex)
log10(x)ใช ้หำค่ำ log ฐำน 10 ของ x
exp(x)
ใช
้หำค่
ำ
e
ยกก
ำลั
ง
x
x
(e ) (e = 2.718282)
fabs(x)
ใช
้หำค่
ำ
สั
ม
บู
ร
ณ์
ข
อง
x
(absolute value) |x|
่
ceil(x)
ใช
้หำค่
ำ
เลขจ
ำนวนเต็
ม
ที
มี
ค่ำมำกกว่ำหรือ
เท่ำกับค่ำ x
่ คำ่
floor(x)
ใช
้หำค่
ำ
เลขจ
ำนวนเต็
ม
ที
มี
40
น้อยกว่ำหรือ
่
ฟั
งก
์ช
ันเกี
ยวกับสตริ
ง
ก
์
(String
Function)
่
ฟั
ง
ก
์ช
ันเกี
ยวกั
บ
string
จะอยู
ใ
่
น
แฟ้ มข ้อมูล string.h จึง
ต
้องระบุ
#include
<string.h>
ในตอนต
้น
่
ของโปรแกรมซึงจะมี
ฟังก ์ช ันต่ำงๆ ดังนี ้ คือ
strcpy (str1 , str2)
ใช ้ในกำร copy ค่ำ str2 ไปยัง str1
ตัวอย่ำง strcpy(str1,”Kmutt”);
strcat(str1 , str2)
่
ใช
้ในกำรเชื
อมต่
อ
str1
และ
str2
ผลลั
พ
ธ
์จะ
ถูกเก็บไว ้ใน str1 ดัง
41
strlen(str)
ใช ้หำค่ำควำมยำวของ string
strcmp(str1 , str2)
ใช
้ในกำรเปรี
ย
บเที
ย
บ
str1
และ
str2
โดยใช
้
ค่ำ ASCII เป็ นหลัก
ผลของกำรเปรียบเทียบจะเป็ นดังนี ้
ถ
้ำ
str1
<
str2
จะได
้ผลลั
พ
ธ
์น้
อ
ยกว่
ำ
ศูนย ์
ถ ้ำ str1 = str2 จะได ้ผลลัพธ ์เป็ นศูนย ์
ถ
้ำ
str1
>
str2
จะได
้ผลลั
พ
ธ
์มำกกว่
ำ
ศูนย ์
42
String Comparison
strcmp(“thrill”, “throw”);
negative integer
strcmp(“read”, “readable”);
negative integer
strcmp(“shrimp”, “crab”);
positive integer
strcmp(“end”, “end”);
zero
strncmp:
returns a
returns a
returns a
returns
Prototype: int strncmp(char *s1, char
*s2, unsigned n);
Purpose: Compares the first n characters
of s1 and s2 returning positive, zero, and
43
negative values as does strcmp.
่
ฟั งก ์ช ันเกียวกับตั
วอ ักษร
่
ฟั
ง
ก
์ช
ันเกี
ยวกั
บ
ตั
ว
อั
ก
ษรจะอยู
ใ
่
น
แฟ้ มข ้อมูล ctype.h จึง
ต
้องระบุ
#include
<ctype.h>
ในตอนต
้น
่
ของโปรแกรมซึงจะมี
ฟังก ์ช ันต่ำงๆ ดังนี ้ คือ
่
ยนตั
ว
อั
ก
ษร
tolower(ch)
ใช
้ในกำรเปลี
จำกตัวใหญ่เป็ น
ตัวเล็ก
่
toupper(ch)
ใช
้ในกำรเปลี
ยนตั
ว
อั
ก
ษร
จำกตัวเล็กเป็ นตัว
ใหญ่
isalnum(ch)
จะให
้ค่
ำ
เลขจ
ำนวนเต็
ม
่
ซึงไม่เท่ำกับศูนย ์ ถ ้ำ
ch
มี
ค
ำ
่
เป็
นตั
ว
อั
ก
ษร
44
หรือตัวเลข และ จะให ้
isalpha(ch)
่ เท่ำกับศูนย ์ ถ ้ำ ch
จะให
้ค่
ำ
เลขจ
ำนวนเต็
ม
ซึ
งไม่
มีคำ่ เป็ นตัวอักษร
และ
จะให
้ค่
ำ
เป็
นศู
น
ย
์
ถ
้ำ
ch
ไม่
ไ
ด
้มี
ค
ำ
่
เป็
น
ตัวอักษรรวมถึง
่
เครืองหมำยต่
ำงๆ
isdigit(ch)
่ เท่ำกับศูนย ์ ถ ้ำ ch
จะให
้ค่
ำ
เลขจ
ำนวนเต็
ม
ซึ
งไม่
มีคำ่ เป็ นตัวเลข
0
9
และ
จะให
้ค่
ำ
เป็
นศู
น
ย
์
ถ
้ำ
ch
ไม่
ไ
ด
้มี
ค
ำ
่
เป็ นตัวเลข
islower(ch)
่ เท่ำกับศูนย ์ ถ ้ำ ch
จะให
้ค่
ำ
เลขจ
ำนวนเต็
ม
ซึ
งไม่
มีคำ่ เป็ นตัวอักษร
ตั
ว
เล็
ก
และ
จะให
้ค่
ำ
เป็
นศู
น
ย
์
ถ
้ำ
ch
เป็
น
่
ตัวอักษรอืนๆ
isupper(ch)
45
ispunct(ch)
่ เท่ำกับศูนย ์ ถ ้ำ ch
จะให
้ค่
ำ
เลขจ
ำนวนเต็
ม
ซึ
งไม่
มีคำ่ เป็ น
่
เครื
องหมำยวรรคตอนและ
จะให
้ค่
ำ
เป็
นศู
น
ย
์
ถ
้ำ
ch ไม่เป็ น
่
เครืองหมำยวรรคตอน
isxdigit(ch)
่ เท่ำกับศูนย ์ ถ ้ำ ch
จะให
้ค่
ำ
เลขจ
ำนวนเต็
ม
ซึ
งไม่
มีคำ่ เป็ นตัวเลข
ในระบบเลขฐำนสิ
a-f และ จะให ้ค่ำ บหกได ้แก่ 0 - 9 , A-F หรือ
่
เป็ นศูนย ์ ถ ้ำ ch เป็ นตัวอักษรอืนๆ
isprint(ch)
iscntrl(ch)
isgraph(ch)
46
่ ทัวไป
่
ฟั งก ์ช ันอืนๆ
่ นอกจำกทีกล่
่ ำวมำแล ้ว จะ
ฟั
ง
ก
์ช
ันอื
นๆ
อยูใ่ นแฟ้ มข ้อมูล
stdlib.h
จึ
ง
ต
้องระบุ
#include
<stdlib.h> ในตอนต ้นของ
่
โปรแกรมซึงจะมี
ฟังก ์ช ันต่ำงๆ ดังนี ้ คือ
่
abs(x)
ใช
้หำค่
ำ
สั
ม
บู
ร
ณ์
ข
อง
x
ซึ
ง
เป็ นเลขจำนวนเต็ม
่
labs(x)
ใช
้หำค่
ำ
สั
ม
บู
ร
ณ์
ข
อง
x
ซึ
ง
เป็ นเลขจำนวนเต็ม
ยำว
abort()
ใช
้ในกำรยกเลิ
ก
กำรท
ำงำน
ของโปรแกรม
้น และมีข ้อควำม
ขณะนั
Abnormal program
47
termination ปรำกฏ
่ ทัวไป(ต่
่
ฟั งก ์ช ันอืนๆ
อ)
่ ยน
่ string เป็ น
atof(str)
ท
ำหน้
ำ
ที
เปลี
ข ้อมูลเลขทศนิ ยม
ละเอียดสองเท่ำ
่ ยน
่ string เป็ น
atoi(str)
ท
ำหน้
ำ
ที
เปลี
ข ้อมูลเลขจำนวน
เต็ม
่ ยน
่ string เป็ น
atol(str)
ท
ำหน้
ำ
ที
เปลี
ข ้อมูลเลขจำนวน
เต็มยำว
clrscr()
ใช
้ในกำร
clear
จอภำพให
้
ว่ำง
่
clreol()
ใช
้ลบข
้อควำมในบรรทั
ด
ที
cursor อยูไ่ ปจนจบ
48
บรรทัดนั้น
Converting a String Into an int
Using atoi
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str1[] = "124z3yu87";
char str2[] = "-3.4";
char *str3 = "e24";
Output:
printf("str1: %d\n", atoi(str1));
str1:
printf("str2: %d\n", atoi(str2));
124
printf("str3: %d\n", atoi(str3));
str2: -3
return 0;
49
่ ทัวไป(ต่
่
ฟั งก ์ช ันอืนๆ
อ)
gotoxy(x , y)
่ cursor ไปยังตำแหน่ งที่
ใช
้ส
ำหร
ับกำรเลื
อน
ต ้องกำรบนจอภำพ
่ x เป็ นตำแหน่ งคอลัมน์ และ y เป็ น
โดยที
ตำแหน่ งบรรทัด
exit(status)
้น ค่ำ
ใช
้ยกเลิ
ก
กำรท
ำงำนของโปรแกรมขณะนั
status ปกติจะมี
ค่
ำ
เป็
นศู
น
ย
์ถ
้ำเป็
นกำรจบโปรแกรมตำมปกติ
่
ส่วนกรณี อนๆ
ื จะ
เป็ นกำรใช ้แทนข ้อผิดพลำดต่ำงๆ
delline()
่
่
่
ใช
้ลบบรรทั
ด
ที
cursor
อยู
แ
่
ล
้วเลื
อนบรรทั
ด
ที
้
50
อยูข
่ ้ำงล่ำงขึนมำ
่ ทัวไป(ต่
่
ฟั งก ์ช ันอืนๆ
อ)
insline()
ใช
้แทรกบรรทั
ด
ว่
ำ
งลงไปใต
้
่
บรรทัดที cursor
อยูอ
่ ก
ี 1 บรรทัด
sizeof(x)
ใช
้ตรวจสอบขนำดของตั
ว
่
แปรว่ำมีขนำดกี
ไบท ์
system(“command”)
ให
้ผู
เ
้
ขี
ย
น
โปรแกรมสำมำรถใช ้
่
ค
ำสั
งใน
่ ่
MS-DOS ได ้ขณะทีอยู
ในภำษำ
C
ตัวอย่ำง
51
system(“dir”);
่ เ้ ขียนโปรแกรมกาหนดขึน
้
2.
ฟั
งก
์ช
ันที
ผู
เอง
่
นอกจำกฟั
ง
ก
์ช
ันมำตรฐำนในภำษำ
C
ที
ได ้กล่ำวไปแล ้ว
้น้ ผูเ้ ขียนโปรแกรมสำมำรถกำหนดฟังก ์ช ัน
นั
ขึนมำใช ้งำนได ้
เองตำมวั
ต
ถุ
ป
ระสงค
์ของผู
เ
้
ขี
ย
นโปรแกรม
ลักษณะกำรทำงำน
ของฟั
ง
ก
์ช
ันจะมี
ก
ำรส่
ง
ค่
ำ
หรื
อ
ร
ับค่
ำ
ระหว่
ำ
ง
โปรแกรมหลัก
่ ้ำงขึน้ รูปแบบกำร
(main)
กั
บ
ฟั
ง
ก
์ช
ันที
สร
กำหนดฟังก ์ช ัน
function
type
function_name
(data_type var…)
{ …
…
52
statement;
้
่
นเองมี
ก
ำหนดขึ
กำรเรี
ย
กใช
้ฟั
ง
ก
์ช
ันที
ร
ป
ู
แบบ
้
ดังนี
function_name
(arg1 , arg2 , arg3 ,
… , arg
)
n
ลั
ษณะกำรเขี
ยนโปรแกรมหลัก main( ) และ
ฟักงก
์ช ัน
main( )
{ ...
statement;
…
function_name( );
…
}
function_name( )
{ …
statement;
…
return ( );
53
ต ัวแปร Local และต ัวแปร Global
่ ำหนดขึน้
ตั
ว
แปร
Local
เป็
นตั
ว
แปรที
ก
ภำยใน block
่
่ แปร
(เครื
องหมำย
{
}
)
ของฟั
ง
ก
์ช
ัน
ซึ
งตั
Local จะมีผลเฉพำะ
ในฟังก ์ช ันนั้นๆ
่ ้ร่วมกันได ้
ตั
ว
แปร
Global
เป็
นตั
ว
แปรที
ใช
ทุกฟังก ์ช ันใน
โปรแกรมเดี
ฟังก ์ช ันใดๆ ยวกัน โดยจะถูกเขียนไว ้นอก
#include <stdio.h>
Global
int a,b,c;
float x,y,z; variables
main( )
{
int m,n;
Local
54
LOCAL VARIABLES
• Each function has its own
local variables.
• Multiple functions (including
main()) can have
the local variables with the
same name.
• Although they may have
55
EXAMPLE: LOCAL VARIABLE
#include <stdio.h>
void myfunc(void);
int main()
{
int x=1;
printf(“main local variable x is %d”,x);
myfunc();
printf(“main local variable x is still %d”,x);
return 0;
}
void myfunc(void)
{
int x;
x=2;
printf(“ myfunc local variable x is %d”,x);
}
56
วิ
ธ
ก
ี
ารเขี
ย
นโปรแกรมแบบ
Recursion
้
(การเรียกซา)
้
เป็
นวิ
ธ
ก
ี
ำรเขี
ย
นฟั
ง
ก
์ช
ันขึ
นมำใช
้เองและ
ภำยในฟังก ์ช ัน
้นมีกำรเรี
้
้
นั
ย
กใช
้ฟั
ง
ก
์ช
ันนั
นซ
ำภำยในตั
ว
ของ
่
่
มันเอง สิงทีจะ
้
่ ยนแบบ
ต
้องก
ำหนดขึ
นภำยในฟั
ง
ก
์ช
ันเมื
อเขี
recursion คือ
1. Base cases
2. Making progress
ตัวอย่ำง
fac(int x)
{
if(x == 0)
return 1;
57
Preprocessor
่
่
เป็
นกำรน
ำเอำค
ำสั
งอื
นๆ
มำรวมเข
้ำกั
บ
่
โปรแกรมทีผูเ้ ขียน
้
นเอง
ก่
อ
นท
ำกำร
โปรแกรมเขี
ย
นขึ
compile
โปรแกรม
่
กำรเขี
ย
นค
ำสั
ง
preprocessor
จะมี
่
เครืองหมำย # นำหน้ำ
่
่
และจบคำสังโดยไม่
ต ้องมีเครืองหมำย
;
ใน
preprocessor
จะประกอบด
้วย
preprocessor
่
directive
อยู
จ
่
ำนวนมำก
ซึ
งจะแนะน
ำบำงตั
ว
้
ให ้ทรำบดังนี
# define
่
ใช
้ก
ำหนดค่
ำ
ข
้อมู
ล
ให
้กั
บ
ชื
อแมคโคร
(macro_name) ที่
58
้
้
่
้
ตังขึน ถ ้ำมีกำรเรียกใช ้ชือแมคโครนัน ก็จะมีคำ่
่
ชื
อแมคโคร
(macro_name)
อำจจะ
เขียนด ้วยอักษรตัว
่ ยนมเขียนด ้วย
ใหญ่
ห
รื
อ
ตั
ว
เล็
ก
ก็
ไ
ด
้
แต่
ท
นิ
ี
ตัวอักษรตัวใหญ่
Defined constants (#define)
You
can
define
your
own
names
for constants that you
use
very
without having to
resort
to often
memoryconsuming
variables, simply by
using the #define
preprocessor
directive. Its format
is:
#define identifier value
For example:
#define PI 3.14159265
59
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 : result2
If condition is true the expression
will return result1, if it is not it will
return result2.
7==5 ? 4 : 3 // returns 3, since 7
is not equal to 5. 7==5+2 ? 4 : 3
// returns 4, since 7 is equal to
5+2.
5>3 ? a : b // returns the value of
60
a, since 5 is greater
#include
ใช
้บอกให
้ตั
ว
แปลภำษำ
(compiler)
น
ำ
่
แฟ้ มข ้อมูลอืนมำ
่ อยู
่ ภ
่ ยนขึน้
ใช
้รวมกั
บ
ค
ำสั
งที
่
ำยในโปรแกรมที
เขี
เอง
่ งนี ้
มีรป
ู แบบคำสังดั
#include “file_name”
หรือ #include <file_name>
61
คาสัง่ switch( )
่
กำรเขี
ย
นโปรแกรมที
ประกอบด
้วยหลำย
่
เงือนไขสำมำรถ
่ อไปนี ้
ใช ้คำสัง่ switch() ได ้ ดังรูปแบบคำสังต่
switch (v) {
case constant1 :
statement;
break;
case constant2 :
statement;
break;
.
.
default :
statement;
}
62
switch Statement
• To select one of several
alternatives.
• Selection is based on the value
of an expression.
• Expression could be a single
value.
• The type of expression can be
either int or char type,
63
switch Statement
Syntax:
switch (expression){
case const-expr:
statements;
break;
case const-expr:
statements;
break;
.
case const-expr:
statements;
break;
default:
statements;
break; }
64
#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); }
}
65
input ship code : f
#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.5
output c = 2.250000
66
ข้อมู ลชนิ ดโครงสร ้าง(Structure)
เป็
นกำรรวมกลุ
ม
่
ของตั
ว
แปรเข
้ำด
้วยกั
น
่
ภำยใต ้ชือโครง
สร ้ำงเดียวกัน โดยมีรป
ู แบบดังนี ้
struct structure_name {
type var_name-1;
type var_name-2;
.
.
type var_name-n;
} sturcture_var;
67
ตัวอย่ำง
struct student_data {
int id;
char name[40];
char address[50];
int age;
} student;
่
้
กำรอ
้ำงถึ
ง
ตั
ว
แปรที
อยู
ใ่ นโครงสร ้ำง มีรป
ู แบบ
ดังนี
structure_var.var_name
เช่น
student.name
68
กำรกำหนดตัวแปรให
้มีโครงสร ้ำงเหมือนกับ
่
กลุม
่ โครงสร ้ำงที
มีอยูแ่ ล ้ว มีรป
ู แบบดังนี ้
struct structure_name
structure_var;
เช่น
struct student_data
chem,math;
69
ข้อมู ลแบบยู เนี ยน(union)
่ งคล ้ำยกับข ้อมูลแบบ
เป็
นข
้อมู
ล
ชนิ
ด
หนึ
โครงสร ้ำง โดย
สมำชิ
ก
ทุ
ก
ตั
ว
จะใช
้หน่
ว
ยควำมจ
ำเดี
ย
วกั
น
โดย
้
มีรป
ู แบบดังนี
union union_name {
type var_name-1;
type var_name-2;
.
.
type var_name-n;
} union_var;
70
ตัวอย่ำง
union data_ab {
int a;
char b;
} var_ab;
กำรกำหนดค่ำหรืออ ้ำงถึงข ้อมูลใน union
var_ab.a = 25;
a
b
71
การเปิ ดแฟ้มข้อมู ล (File)
กำรเปิ ดแฟ้ มข ้อมูลมีรป
ู แบบดังนี ้
FILE *fp
fp = fopen(f_name,mode);
fp
เป็ น้ำงชนิ
fileดpointer
โครงสร
FILE ของข ้อมูลแบบ
่
fopen
เป็
นฟั
ง
ก
์ช
ันที
ใช
้ในกำรเปิ ด
แฟ้ มข ้อมูล
่
f_name เป็ นชือแฟ้
มข ้อมูล
mode เป็ น status ของกำรเปิ ดแฟ้ มข ้อมูล
่
“r” เปิ ดไฟล ์เพือกำรอ่
ำนข ้อมูล
่ นทึกข ้อมูล
“w” สร ้ำงไฟล ์ใหม่เพือบั
่ มข
่ ้อมูลต่อท ้ำยไฟล ์
“a” เปิ ดไฟล ์เพือเพิ
72
รู ปแบบข้อมู ลกาหนดได้ 2 แบบ
t บันทึกข ้อมูลแบบข ้อควำม Text
b บันทึกข ้อมูลแบบเลขฐำนสอง
Binary
การปิ ดแฟ้มข้อมู ล
fclose(fp);
ฟั งก ์ช ัน fprintf() และ fscanf()
เป็ นกำรเขีย้ นและอ่ำนข ้อมูลกับไฟล ์ มี
รูปแบบดงนี
st);
fprintf(fp,control_string,var_li
73
#include <stdio.h>
#include <conio.h>
main()
{
int i;
FILE *mathfile;
mathfile
=
fopen(“a:test.txt”,”wt”);
clrscr()
for(i=1;i<=20;i++)
fprintf(mathfile,”%d\n”,i);
fclose(mathfile);
}
74
#include <stdio.h>
#include <conio.h>
main()
{
int i,a;
FILE *mathfile;
mathfile = fopen(“a:test.txt”,”rt”);
clrscr()
for(i=1;i<=5;i++)
{
fscanf(mathfile,”%d”,&a);
printf(“a[%d] = %d\n”,i,a);
}
fclose(mathfile);
}
75
#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(20,5);printf("record no #
%d",i);
gotoxy(20,6);printf("book id :");
gotoxy(20,7);printf("book name
:");
gotoxy(20,8);printf("author :");
gotoxy(20,9);printf("price :");
gotoxy(32,6);scanf("%d",&id); 76
gotoxy(32,7);scanf("%s",&name);
gotoxy(32,8);scanf("%s",&author);
gotoxy(32,9);scanf("%d",&price);
fprintf(stfile,"%d %s %s
%d\n",id,name,author,price);
}
fclose(stfile);
}
77
#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,&a
uthor,&price);
if(feof(stfile)!=0)break;
printf("%-5d%-10d%-20s%20s%d\n",i,id,name,author,price);
}
78
ในกำรใช
้ฟั
ง
ก
์ช
ัน
fopen(
)
จะให
้ค่
ำ
NULL
ถ ้ำไม่สำมำรถเปิ ด
File ได ้
ตัวอย่ำง
#include <stdio.h>
main( )
{
FILE *fp;
If((fp=fopen(“math.dat”,”w”))==N
ULL) {
printf(“cannot
open
file\n”);
return 0;
79
ฟั งก ์ช ัน fputs() และ fgets()
เป็ นกำรเขียนและอ่
ำนข ้อมูล string กับไฟล ์
้
มีรป
ู แบบดังนี
fputs(str , fp);
fgets(str , num , fp);
80
#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(20,5);printf("record no #
%d",i);
gotoxy(20,6);printf("book id :");
gotoxy(20,7);printf("book name
:");
gotoxy(20,8);printf("author :");
gotoxy(20,9);printf("price :");81
gotoxy(32,6);gets(id);
gotoxy(32,7);gets(name);
gotoxy(32,8);gets(author);
gotoxy(32,9);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);
82
#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;
bfile2 = fopen("report.dat","wt");
clrscr();
fprintf(bfile2,"No. Book_id NAME
");
fprintf(bfile2,"AUTHOR
PRICE\n");
for(i=1;;i++)
{
fgets(id,5,bfile);
83
fgets(name,20,bfile);
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,"%-4d%-9d%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';
84
ฟั งก ์ช ัน fwrite() และ fread() ในการ
สร ้าง file แบบ record
เป็ นกำรเขีย้ นและอ่ำนข ้อมูลกับไฟล ์ มี
รูปแบบดังนี
fwrite(pt , bytes , n , fp);
fread(pt , bytes , n , fp);
pt เป็ น pointer ของตัวแปร
bytes เป็ นขนำดของตัวแปร
n เป็ นจำนวนข ้อมูล
fp เป็ น file pointer
85
#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(20,5);printf("record no #
%d",i);
gotoxy(20,6);printf("book id :");
gotoxy(20,7);printf("book name
:");
86
gotoxy(20,9);printf("price :");
gotoxy(32,6);scanf("%d",&book.id);
if(book.id==0)break;
gets(sp);
gotoxy(32,7);gets(book.name);
gotoxy(32,8);gets(book.author);
gotoxy(32,9);scanf("%d",&book.price
);
fwrite(&book,sizeof
book,1,stfile);
}
fclose(stfile);
}
87
#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
88
PRICE\n");
for(i=1;;i++)
{
fread(&book,sizeof book,1,stfile);
if(feof(stfile)!=0)break;
printf("%-4d%-9d%20s",i,book.id,book.name);
printf("%-20s
%d\n",book.author,book.price);
}
fclose(stfile);
}
89