Tải bản đầy đủ (.pdf) (39 trang)

KIỂU DỮ LIỆU CÓ CẤU TRÚC TRONG C

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (381.75 KB, 39 trang )

KIỂU DỮ LIỆU CÓ CẤU TRÚC TRONG C
1.

Kiểu Mảng

2.

Mảng và xâu kí tự

3.

Kiểu Bản ghi

4.

Mảng và bản ghi

5.

Kiểu Union

6.

Thao tác bit

7.

Kiểu Enum

0


1. KIỂU MẢNG
Các mảng
• Là cấu trúc gồm các phần tử dữ liệu có liên quan
với nhau
• Các thực thể tĩnh (Static) – kích thước khơng thay
đổi trong suốt chương trình
(Phân biệt với: Cấu trúc dữ liệu động (Dynamic)

1


Tên của mảng (tất
cả các phần tử có
chung tên c)

Khái niệm mảng
c[0]

-45

c[1]

6

c[2]

0

c[3]


72

c[4]

1543

c[5]

-89

• Tên mảng

c[6]

0

c[7]

62

• Số vị trí

c[8]

-3

c[9]

1


• Nhóm của định vị bộ nhớ liên tiếp nhau
• Cùng chung tên và kiểu dữ liệu

Tham chiếu đến phần tử, cụ thể

Định dạng:

c[10]

6453

c[11]

78

arrayname[ position number ]

• phần tử đầu tiên có vị trí 0
• n phần tử mảng với tên c:
– c[ 0 ], c[ 1 ]...c[ n – 1 ]

Số vị trí của
phần tử trong
mảng c

2

Các phần tử trong mảng giống như các biến
c[ 0 ] = 3;
printf( "%d", c[ 0 ] );

• Thực hiện thao tác trong ngoặc [] để xác định chỉ số.
+ Nếu x = 3 thì c[ 5 - 2 ] == c[ 3 ] == c[ x ]
+ Chỉ số của mảng có thể xác định bằng biểu thức
toán học

3


Khai báo mảng
Khi khai báo mảng
• Tên mảng
• Kiểu mảng
• Số phần tử
Cú pháp: arrayType arrayName[ numberOfElements ];

• Ví dụ:
int c[ 10 ];
float myArray[ 3284 ];

Khai báo nhiều mảng có cùng kiểu
• Cú pháp tương tự như khai báo biến
• Ví dụ:
int b[ 100 ], x[ 27 ];

4

Khai báo và khởi tạo mảng
Khởi tạo mảng: khai báo và gắn giá trị các phần tử
int n[ 5 ] = { 1, 2, 3, 4, 5 };
• Nếu khơng đủ các biến thì các phần tử bên phải nhất bằng 0

int n[ 5 ] = { 0 } // Tất cả các phần tử bằng 0
• Nếu q nhiều phần tử thì báo lỗi cú pháp
• C khơng kiểm tra giới hạn của mảng
• Nếu bỏ qua kích thước, sử dụng mặc định số phần tử khởi tạo
int n[ ] = { 1, 2, 3, 4, 5 };
. Khởi tạo 5 phần tử, do đó mảng có 5 phần tử

5


Ví dụ: Khai báo và khởi tạo mảng
1 /* Fig. 6.4: fig06_04.c
Initializing an array with an initializer list */

2

Program Output

3 #include <stdio.h>
4

Element

Value

5 /* function main begins program execution */
6 int main()
7 {
8


/* use initializer list to initialize array n */

9

int n[ 10 ] = { 32,
32, 27,
27, 64,
64, 18,
18, 95,
95, 14,
14, 90,
90, 70,
70, 60,
60, 37 };

10

int i; /* counter */

11
12

printf( "%s%13s\
"%s%13s\n",
n", "Element",
"Element", "Value" );

13
14


/* output contents of array in tabular format */

15

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

16
17

printf( "%7d%13d\
"%7d%13d\n",
n", i, n[ i ] );
} /* end for */

18
19

return 0; /* indicates successful termination */

20

0

32

1

27


2

64

3

18

4

95

5

14

6

90

7

70

8

60

9


37

21 } /* end main */

Mối liên hệ giữa mảng và con trỏ trong C
Ví dụ: Tên của array chính là &array[ 0 ] (địa chỉ của phần tử đầu tiên trong mảng)
1 /* Fig. 6.12: fig06_12.c
2

The name of an array is the same as &array[ 0 ] */

3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 {
8

char array[ 5 ]; /* define an array of size 5 */

9
10

printf( "

array = %p\
%p\n&array[0] = %p\
%p\n"

11


"

&array = %p\
%p\n",
n",

12

array, &array[ 0 ], &array );

13
14

return 0; /* indicates successful termination */

15
16 } /* end main */

array = 0012FF78
&array[0] = 0012FF78
&array = 0012FF78


Mảng nhiều chiều
Mảng nhiều chiều
• Bảng với các hàng và các cột (m hàng và n cột)
• Giống như ma trận: chỉ số đầu là hàng (row), sau đó là cột
(column)
Column 0


Row 0
Row 1
Row 2

Column 1 Column 2

Column 3

a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Chỉ số cột-Column
Tên mảng
Chỉ sô hàng-Row
8

Mảng nhiều chiều
Khởi tạo
• int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };

1

2

3

4

• Khởi tạo theo hàng trong dấu {}

• Nếu khơng đủ, các phần tử còn lại nhận giá trị 0

1

0

3

4

int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };

Tham chiếu các phần tử
• Chỉ ra hàng và cột
printf( "%d", b[ 0 ][ 1 ] );

• Nhập giá trị cho phần tử (i,j) của mảng
scanf(“%d”, &b[i][j]);
9


Ví dụ: Khởi tạo mảng đa chiều
1

/* Fig. 6.21: fig06_21.c
Initializing multidimensional arrays */

2
3


#include <stdio.h>

4
5

void printArray( const int a[][ 3 ] ); /* function prototype */

6
7

/* function main begins program execution */

8

int main()

9

{

10

/* initialize array1, array2, array3 */

11

int array1[ 2 ][ 3 ] = { { 1 , 2 , 3 }, { 4 , 5 , 6 } };

12


int array2[ 2 ][ 3 ] = { 1 , 2 , 3 , 4 , 5 };

13

int array3[ 2 ][ 3 ] = { { 1 , 2 }, { 4 } };

14
15

printf( "Values in array1 by row are:\
are: \ n" );

16

printArray( array1 );

17
18

printf( "Values in array2 by row are:\
are: \ n" );

19

printArray( array2 );

20
21

printf( "Values in array3 by row are:\

are: \ n" );

22

printArray( array3 );

23
return 0 ; /* indicates successful termination */

24
25
26

} /* end main */

27

28 /* function to output array with two rows and three columns */
29 void printArray( const int a[][ 3 ] )
30 {
31

int i; /* counter */

32

int j; /* counter */

Program Output


33
34

/* loop through rows */

35

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

36
37

/* output column values */

38

for ( j = 0; j <= 2; j++ ) {

39
40

printf( "%d ",
", a[ i ][ j ] );
} /* end inner for */

41
42
43

printf( "\n" ); /* start new line of output */

} /* end outer for */

44
45 } /* end function printArray */

Values in array1 by row are:
1 2 3
4 5 6
Values in array2 by row are:
1 2 3
4 5 0
Values in array3 by row are:
1 2 0
4 0 0


Truyền mảng cho hàm
Để truyền một mảng cho hàm, chỉ ra tên của mảng,
không sử dụng cặp “[]”
int myArray[ 24 ];
myFunction( myArray, 24 );

– Kích thước của mảng cần được truyền qua hàm

• Mảng được truyền thơng qua lời gọi tham chiếu
• Tên của mảng là địa chỉ phần tử đầu tiên
• Hàm biết được nơi lưu trữ mảng
– Thực hiện thay đổi tại vị trí chứa mảng trong bộ nhớ

Truyền các phần tử mảng

• Truyền thơng qua lời gọi bởi giá trị (truyền theo trị)
• Truyền tên mảng cùng chỉ số tới hàm (ví dụ: myarray[ 3 ])
12

Truyền mảng cho hàm
Khai báo nguyên mẫu hàm (function prototype) để
truyền mảng cho hàm
void modifyArray( int b[], int arraySize );

• Có thể bỏ qua tên mảng trong khai báo nguyên mẫu hàm
– int b[] có thể được viết int []
– int arraySize có thể được viết đơn giản là int

• Tên của array chính là &array[ 0 ] (địa chỉ của phần tử
đầu tiên trong mảng) do vậy khi truyền mảng (tham
biến) thơng qua gọi hàm khơng cần sử dụng dấu &
Ví dụ gọi hàm với khai báo nguyên mẫu trên:
int a[10], n = 10;
modifyArray( a, n); // không sử dụng &a
13


Ví dụ: Tên của array chính là &array[ 0 ] (địa chỉ của phần tử
đầu tiên trong mảng)
1 /* Fig. 6.12: fig06_12.c
The name of an array is the same as &array[ 0 ] */

2

3 #include <stdio.h>

4
5 /* function main begins program execution */
6 int main()
7 {
char array[ 5 ]; /* define an array of size 5 */

8
9

printf( "

10

array = %p\
%p\n&array[0] = %p\
%p\n"

11

"

12

array, &array[ 0 ], &array );

&array = %p\
%p\n",
n",

13

return 0; /* indicates successful termination */

14
15

16 } /* end main */

array = 0012FF78
&array[0] = 0012FF78
&array = 0012FF78

Ví dụ:
- Truyền mảng b và thay đổi các phần tử của mảng khi gọi hàm (tham chiếu)
- Truyền phần tử của mảng qua hàm (tham trị)
1

/* Fig. 6.13: fig06_13.c
Passing arrays and individual array elements to functions */

2
3

#include <stdio.h>

4

#define SIZE 5

5
6


/* function prototypes */

7

void modifyArray( int b[], int size );

8

void modifyElement( int e );

9
10 /* function main begins program execution */
11 int main()
12 {
13

int a[ SIZE ] = { 0, 1, 2, 3, 4 }; /* initialize a */

14

int i; /* counter */

15
16
17

printf( "Effects of passing entire array by reference:\
reference:\n\nThe "
"values of the original array are:\

are:\n" );

18
19

/* output original array */

20

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

21
22

printf( "%3d",
"%3d", a[ i ] );
} /* end for */

23
24
25

printf( "\n" );


26

/* pass array a to modifyArray by reference */


27

modifyArray( a, SIZE );

28
printf( "The values of the modified array are:\
are:\n" );

29

fig06_13.c (Part 2 of 3)

30
31

/* output modified array */

32

for ( i = 0; i < SIZE
SIZE;
ZE; i++ ) {

33

printf( "%3d",
"%3d", a[ i ] );
} /* end for */

34

35
36

/* output value of a[ 3 ] */

37

printf( "\n\n\nEffects of passing array element "
"by value:\
value:\n\nThe value of a[3] is %d\
%d\n",
n", a[ 3 ] );

38
39

modifyElement( a[ 3 ] ); /* pass array element a[ 3 ] by value */

40
41
42

/* output value of a[ 3 ] */

43

printf( "The value of a[ 3 ] is %d\
%d\n",
n", a[ 3 ] );


44
return 0; /* indicates successful termination */

45
46

47 } /* end main */
48

49 /* in function modifyArray, "b" points to the original array "a"
in memory */

50

51 void modifyArray( int b[], int size )
52 {
int j; /* counter */

53
54
55

/* multiply each array element by 2 */

56

for ( j = 0; j < size;
size; j++ ) {

57


b[ j ] *= 2;

58

} /* end for */

59
60 } /* end function modifyArray */
61
62 /* in function modifyElement, "e" is a local copy of array element
a[ 3 ] passed from main */

63

64 void modifyElement( int e )
65 {
66

/* multiply parameter by 2 */

67

printf( "Value in modifyElement
modifyElement is %d\
%d\n",
n", e *= 2 );

68 } /* end function modifyElement */


- Mảng b sẽ thay đổi giá trị sau khi gọi thực hiện hàm modifyArray
- Phần tử a[3] không thay đổi khi truyền cho biến e khi gọi hàm modifyElement


Effects of passing entire array by reference:
The values of
0 1 2 3
The values of
0 2 4 6

the original array are:
4
the modified array are:
8

Effects of passing array element by value:
The value of a[3] is 6
Value in modifyElement is 12
The value of a[ 3 ] is 6

BÀI TẬP 5.1
Viết các chương trình cài đặt phép toán trên ma trận:
cộng hai ma trận, nhân vô hướng, nhân 2 ma trận,
phép biến đổi sơ cấp trên ma trận.

19


2. MẢNG VÀ XÂU KÍ TỰ
Mảng ký tự

• Xâu “first” là một mảng các ký tự
• Mảng các ký tự có thể được khởi tạo bởi một xâu

char string1[ ] = "first"
– Kết thúc của xâu ký tự '\0' (Null)
– string1 thực tế có 6 phần tử
– Có thể viết tương ứng như sau:
char string1[ ] = { 'f', 'i', 'r', 's', 't', '\0' };
• Có thể truy cập đến từng ký tự : string1[ 3 ] là ký tự ‘s’
• Tên mảng thể hiện địa chỉ của mảng, vì vậy không cần sử dụng ký
tự “&” trong lệnh scanf
scanf( "%s", string2 );
– Đọc các ký tự đến khi gặp ký tự trắng / dấu cách
20
1 /* Fig. 6.10: fig06_10.c
2

Treating character arrays as strings */

3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 {
8

char string1[ 20 ];

/* reserves 20 characters */


9

char string2[] = "string literal";
literal"; /* reserves 15 characters */

10

int i;

/* counter */

11
12

/* read string from user into array string2 */

13

printf("Enter
printf("Enter a string: ");
");

14

scanf( "%s",
"%s", string1 );

15
16


/* output strings */

17

printf( "string1 is: %s\
%s\nstring2 is: %s\
%s\n"

18

"string1 with spaces between characters is:\
is:\n",
n",

19

string1, string2 );

20
21

/* output characters until null character is reached */

22

for ( i = 0; string1[ i ] != '\0';
0'; i++ ) {

23
24

25

printf( "%c ",
", string1[ i ] );
} /* end for */


Khai báo String
• Giống như khai báo một mảng ký tự hoặc một biến kiểu char *
char color[] = "blue";
char *colorPtr = "blue";

Đọc vào xâu
• Sử dụng scanf()
scanf("%s", word);

– Sao chép vào word[]
– Khơng cần & (vì tên xâu là con trỏ)

• Sử dụng gets( )

Xác định độ dài xâu:
size_t strlen( const char *s ): Trả về số ký tự trong xâu s
22

Thư viện chuẩn các hàm xử lý ký tự và xâu kí tự

Thư viện các hàm về kí tự và xâu kí tự
• Thư viện xử lý ký tự: <ctype.h>
• Sử dụng các hàm vào/ra ký tự và xâu (thư viện stdio.h).

• Sử dụng các hàm chuyển đổi xâu (thư viện stdlib.h).
• Sử dụng các hàm xử lý string (thư viện string.h).

23


Thư viện chuẩn các hàm xử lý ký tự
Prototype
int isdigit( int c );
int isalpha( int c );
int isalnum( int c );
int isxdigit( int c );
int islower( int c );
int isupper( int c );
int tolower( int c );
int toupper( int c );
int isspace( int c );

int iscntrl( int c );
int ispunct( int c );
int isprint( int c );
int isgraph( int c );

Description
Returns true if c is a digit and false otherwise.
Returns true if c is a letter and false otherwise.
Returns true if c is a digit or a letter and false otherwise.
Returns true if c is a hexadecimal digit character and false otherwise.
Returns true if c is a lowercase letter and false otherwise.
Returns true if c is an uppercase letter; false otherwise.

If c is an uppercase letter, tolower returns c as a lowercase letter. Otherwise, tolower
returns the argument unchanged.
If c is a lowercase letter, toupper returns c as an uppercase letter. Otherwise, toupper
returns the argument unchanged.
Returns true if c is a white-space character—newline ('\n'), space (' '), form feed
('\f'), carriage return ('\r'), horizontal tab ('\t'), or vertical tab ('\v')—and false
otherwise
Returns true if c is a control character and false otherwise.
Returns true if c is a printing character other than a space, a digit, or a letter and false
otherwise.
Returns true value if c is a printing character including space (' ') and false otherwise.
Returns true if c is a printing character other than space (' ') and false otherwise.

24

Các hàm chuyển đổi
• Trong <stdlib.h> (thư viện chuẩn)

Chuyển đổi string của các số thành các số nguyên (int)
và số thực (float)
Function prototype

Function description

double atof( const char *nPtr );

Converts the string nPtr to double.

int atoi( const char *nPtr );
long atol( const char *nPtr );

double strtod( const char *nPtr, char
**endPtr );
long strtol( const char *nPtr, char
**endPtr, int base );
unsigned long strtoul( const char
*nPtr, char **endPtr, int base );

Converts the string nPtr to int.
Converts the string nPtr to long int.
Converts the string nPtr to double.
Converts the string nPtr to long.
Converts the string nPtr to unsigned long.
25


Các hàm thư viện I/O chuẩn <stdio.h>
Function prototype

Function description

int getchar( void );

Inputs the next character from the standard input and returns it as an integer.

char *gets( char *s );

int putchar( int c );
int puts( const char *s );
int sprintf( char *s, const
char *format, ... );

int sscanf( char *s, const
char *format, ... );

Inputs characters from the standard input into the array s
until a newline or end-of-file character is encountered. A
terminating null character is appended to the array.
Prints the character stored in c.
Prints the string s followed by a newline character.
Equivalent to printf, except the output is stored in the
array s instead of printing it on the screen.
Equivalent to scanf, except the input is read fromthe array
s instead of reading it fromthe keyboard.
26

Thư viện điều khiển string có các hàm:
• Thao tác dữ liệu string
• Tìm kiếm trên string
• Xác định độ dài string

Function prototype

Function description

char *strcpy( char
*s1, const char *s2 )
char *strncpy( char
*s1, const char *s2,
size_t n )
char *strcat( char
*s1, const char *s2 )


Copies string s2 into array s1. The value of s1 is returned.

Copies at most n characters of string s2 into array s1. The value of s1
is returned.
Appends string s2 to array s1. The first character of s2 overwrites the
terminating null character of s1. The value of s1 is returned.
char *strncat( char
Appends at most n characters of string s2 to array s1. The first
*s1, const char *s2,
character of s2 overwrites the terminating null character of s1. The
size_t n )
value of s1 is returned.
27


So sánh các string
• Máy tính so sánh mã số ASCII của ký tự trong xâu
• Xem bảng mã các ký tự (sách lập trình C)
int strcmp( const char *s1, const char *s2 );

• So sánh xâu s1 với s2
• Kết quả trả về của hàm là số âm nếu s1 < s2, 0 nếu s1 == s2
hoặc số dương nếu s1 > s2
int strncmp(const char *s1, const char *s2, size_t n );

• So sánh n ký tự của xâu s1 với s2
• Giá trị kết quả trả về giống hàm strcmp()
28


Các hàm tìm kiếm String từ thư viện chuẩn
Function prototype

Function description

char *strchr( const char *s,
int c );

Locates the first occurrence of character c in string s . If c is found, a
pointer to c in s is returned. Otherwise, a NULL pointer is returned.

size_t strcspn( const char
*s1, const char *s2 );

Determines and returns the length of the initial segment of string s1
consisting of characters not contained in string s2 .

size_t strspn( const char
*s1, const char *s2 );

Determines and returns the length of the initial segment of string s1
consisting only of characters contained in string s2 .

char *strpbrk( const char
*s1, const char *s2 );

Locates the first occurrence in string s1 of any character in string s2 .
If a character from string s2 is found, a pointer to the character in
string s1 is returned. Otherwise, a NULL pointer is returned.


char *strrchr( const char *s,
int c );

Locates the last occurrence of c in string s . If c is found, a pointer to c
in string s is returned. Otherwise, a NULL pointer is returned.

char *strstr( const char *s1,
const char *s2 );

Locates the first occurrence in string s1 of string s2 . If the string is
found, a pointer to the string in s1 is returned. Otherwise, a NULL
pointer is returned.

char *strtok( char *s1, const
char *s2 );

A sequence of calls to strtok breaks string s1 into “tokens”—logical
pieces such as words in a line of text—separated by characters
contained in string s2 . The first call contains s1 as the first argument,
and subsequent calls to continue tokenizing the same string contain
NULL as the first argument. A pointer to the current token is returned
by each call. If there are no more tokens when the function is called,
NULL is returned.
29


Hàm Memory
• Trong <stdlib.h>
• Thao tác, so sánh, tìm kiếm khối của memory
• Có thể thao tác bất kỳ khối dữ liệu nào

Function prototype Function description
void *memcpy( void
*s1, const void *s2,
size_t n );
void *memmove( void
*s1, const void *s2,
size_t n );

Copies n characters from the object pointed to by s2 into the object
pointed to by s1. A pointer to the resulting object is returned.
Copies n characters from the object pointed to by s2 into the object
pointed to by s1. The copy is performed as if the characters were first
copied from the object pointed to by s2 into a temporary array and
then from the temporary array into the object pointed to by s1. A
pointer to the resulting object is returned.
int memcmp( const
Compares the first n characters of the objects pointed to by s1 and s2.
void *s1, const void
The function returns 0, less than 0 or greater than 0 if s1 is equal to,
*s2, size_t n );
less than or greater than s2.
void *memchr( const
Locates the first occurrence of c (converted to unsigned char) in the
void *s, int c,
first n characters of the object pointed to by s. If c is found, a pointer
size_t n );
to c in the object is returned. Otherwise, NULL is returned.
void *memset( void
Copies c (converted to unsigned char) into the first n characters of
*s, int c, size_t n

the object pointed to by s. A pointer to the result is returned.
);
30

Xâu kí tự làm tham biến của hàm
1

/* Fig. 7.10: fig07_10.c

2

Converting lowercase letters to uppercase letters

3

using a nonnon-constant pointer to nonnon-constant data */

4
5

#include <stdio.h>

6

#include <ctype.h>

7
8

void convertToUppercase( char *sPtr ); /* prototype */


9
10 int main()
11 {
12

char string[] = "characters and $32.98";
$32.98"; /* initialize char array */

13
14

printf( "The string before conversion is: %s",
%s", string );

15

convertToUppercase( string );

16

printf(
printf( "\nThe string after conversion is: %s\
%s\n",
n", string );

17
18

return 0; /* indicates successful termination */


19
20 } /* end main */
21

31


22 /* convert string to uppercase letters */
23 void convertToUppercase( char *sPtr )
24 {
25

while ( *sPtr != '\0' ) { /* current character is not '\
'\0' */

26
27
28
29

if ( islower( *sPtr ) ) {

/* if character is lowercase, */

*sPtr = toupper( *sPtr ); /* convert to uppercase */
} /* end if */

30
31

32

++sPtr; /* move sPtr to the next character */
} /* end while */

33
34 } /* end function convertToUppercase */

The string before conversion is: characters and $32.98
The string after conversion is: CHARACTERS AND $32.98

BÀI TẬP 5.2
Viết chương trình để tạo một xâu kí tự, là xâu đảo
ngược của một xâu bất kì được nhập vào từ bàn phím.

33


Mảng , Con trỏ và Xâu kí tự
Các phần tử của array có thể là con trỏ
Ví dụ: array của các xâu (strings)
char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" };



Strings là các con trỏ tới ký tự đầu tiên

• char * : mỗi phần tử của suit là một con trỏ char




Các string được lưu trữ là mảng suit

suit[0]

’H’

’e’

’a’

’r’

’t’

’s’

’\0’

suit[1]

’D’

’i’

’a’

’m’

’o’


’n’

’d’

suit[2]

’C’

’l’

’u’

’b’

’s’

’\0’

suit[3]

’S’

’p’

’a’

’d’

’e’


’s’

’s’

’\0’

’\0’

• Mảng suit có kích thước cố định, nhưng con trỏ string có thể là kích thước

bất kỳ

34

Hàm tính kích thước của biến và con trỏ
sizeof
• Trả về kích thước là số byte của biến
• Nếu sizeof( int ) bằng 4 bytes, thì
– int myArray[ 10 ];
– printf( "%d", sizeof( myArray ) );
– sẽ in ra là 40

sizeof Có thể sử dụng với tham số là:
• Tên biến
• Tên kiểu
• Giá trị hằng số

Ví dụ 716: Viết chương trình tính kích thước của array float
gồm 20 phần tử và kích thước của con trỏ đến array

35


1

/* Fig. 7.16: fig07_16.c
Sizeof operator when used on an array name

2

returns the number of bytes in the array. */

3
4

#include <stdio.h>

5
6

size_t getSize( float *ptr ); /* prototype */

7
8

int main()

9

{

float array[ 20 ]; /* create array */

10
11

printf( "The number of bytes in the array is %d"

12
13

"\nThe number of bytes returned by getSize is %d\
%d\n",
n",

14

sizeof(
sizeof( array ), getSize( array ) );

15
return 0; /* indicates successful termination */

16
17

18 } /* end main */
19
20 /* return size of ptr */
21 size_t getSize( float *ptr )
22 {

return sizeof(
sizeof( ptr );

23
24

25 } /* end function getSize */

The number of bytes in the array is 80
The number of bytes returned by getSize is 4

1

/* Fig. 7.17: fig07_17.c
Demonstrating the sizeof operator */

2
3

#include <stdio.h>

4
5

int main()

6

{


7

char c;

/* define c */

8

short s;

/* define s */

9

int i;

/* define i */

10

long l;

/* define l */

11

float f;

/* define f */


12

double d;

/* define d */

13

long double ld;

/* define ld */

14

int array[ 20 ];

/* initialize array */

15

int *ptr = array; /* create
create pointer to array */

16
17

printf( "

sizeof c = %d\
%d\tsizeof(char)


= %d"

18

"\n

sizeof s = %d\
%d\tsizeof(short) = %d"

19

"\n

sizeof i = %d\
%d\tsizeof(int) = %d"

20

"\n

sizeof l = %d\
%d\tsizeof(long) = %d"

21

"\n

sizeof f = %d\
%d\tsizeof(float) = %d"


22

"\n

sizeof d = %d\
%d\tsizeof(double) = %d"

23

"\n

24

"\n sizeof array = %d"
%d"

25

"\n

sizeof ld = %d\
%d\tsizeof(long double) = %d"
sizeof ptr = %d\
%d\n",
n",


26


sizeof c, sizeof(
sizeof( char ), sizeof s,

27

sizeof(
sizeof( short ), sizeof i, sizeof(
sizeof( int ),

28

sizeof l, sizeof(
sizeof( long ), sizeof f,

29

sizeof(
sizeof( float ), sizeof d, sizeof(
sizeof( double ),

30

sizeof ld, sizeof(
sizeof( long double ),

31

sizeof array, sizeof ptr );

32

33

return 0; /* indicates successful termination */

34
35 } /* end main */

sizeof c
sizeof s
sizeof i
sizeof l
sizeof f
sizeof d
sizeof ld
sizeof array
sizeof ptr

=
=
=
=
=
=
=
=
=

1
2
4

4
4
8
8
80
4

sizeof(char) = 1
sizeof(short) = 2
sizeof(int) = 4
sizeof(long) = 4
sizeof(float) = 4
sizeof(double) = 8
sizeof(long double) = 8

Con trỏ và mảng
Cấp phát động cho mảng (<alloc.h>)
• Hàm cấp phát vùng bộ nhớ gồm n byte:
void *malloc(unsigned n)
• Giải phóng vùng nhớ
void free(void *ptr)
Ví dụ:
int *IntArray;
printf(“Size of array:”); scanf(“%d”, &n);
IntArray = (int*) malloc(n*sizeof(int));

39




×