double strtod const char *nPtr, char**endPtr ; Converts the stringnPtr todouble.long strtol const char *nPtr, char**endPtr, int base ; Converts the stringnPtr tolong.unsigned long strtou
Trang 2Số vị trí của phần tử trong mảng c
c[6]
-4560721543-89062-31645378
Trang 41 /* Fig 6.4: fig06_04.c /* Fig 6.4: fig06_04.c
2 Initializing an array with an initializer list */ Initializing an array with an initializer list */
3 #include <stdio.h> <stdio.h>
4
5 /* function main begins program execution */ /* function main begins program execution */ 6 int main() main() 7 { {
8 /* use initializer list to initialize array n */ /* use initializer list to initialize array n */
9 int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; }; 10 int i; /* counter */ /* counter */ 11
12 printf( "%s%13s\"%s%13s\\n"n", "Element", "Value" ); ); 13
14 /* output contents of array in tabular format *//* output contents of array in tabular format */ 15 for ( i = 0; i < i < 10; i++ ) {; i++ ) { 16 printf( "%7d%13d"%7d%13d\\\n"n", i, n[ i ] );, i, n[ i ] ); 17 } /* end for *//* end for */ 18 19 return ; /* indicates successful termination *//* indicates successful termination */ 20 21 } /* end main *//* end main */ Element Value 0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37
Program Output Ví d ụ : Khai báo và kh ở i t ạ o m ả ng 1 /* Fig 6.12: fig06_12.c/* Fig 6.12: fig06_12.c 2 The name of an array is the same as &array[ 0 ] */ The name of an array is the same as &array[ 0 ] */ 3 #include <stdio.h> <stdio.h> 4
5 /* function main begins program execution *//* function main begins program execution */ 6 int main() main() 7 {{
8 char array[ 5 ]; /* define an array of size 5 */ /* define an array of size 5 */
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)
Trang 5a[ 0 ][ 1 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ]
a[ 0 ][ 2 ] a[ 1 ][ 2 ]
a[ 2 ][ 2 ]
a[ 0 ][ 3 ] a[ 1 ][ 3 ] a[ 2 ][ 3 ]
Chỉ sô hàng-Row Tên mảng
Trang 61 /* Fig 6.21: fig06_21.c/* Fig 6.21: fig06_21.c
2 Initializing multidimensional arrays */Initializing multidimensional arrays */
3 #include <stdio.h> <stdio.h>
4
5 void printArray( const int a[][ 3 ] ); /* function prototype *//* function prototype */ 6
7 /* function main begins program execution *//* function main begins program execution */ 8 int main() main() 9 {{
10 /* initialize array1, array2, array3 *//* 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:"Values in array1 by row are:\\\n"n" ); ); 16 printArray( array1 ); printArray( array1 ); 17 18 printf( "Values in array2 by row are:"Values in array2 by row are:\\\n"n" ); ); 19 printArray( array2 ); printArray( array2 ); 20 21 printf( "Values in array3 by row are:"Values in array3 by row are:\\\n"n" ); ); 22 printArray( printArray( array3 );array3 );array3 ); 23 24 return ; /* indicates successful termination *//* indicates successful termination */ 25 26 } /* end main *//* end main */ 27 Ví dụ: Khởi tạo mảng đa chiều Program Output 28 /* function to output array with two rows and three columns *//* function to output array with two rows and three columns */ 29 void printArray( const int a[][ 3 ] ) ] )
30 { {
31 int i; /* counter */ /* counter */
32 int j; /* counter */ /* counter */
33
34 /* loop through rows */ /* loop through rows */
35 for ( i = 0; i <= 1; ; i++ ) { i++ ) { i++ ) {
36
37 /* output column values */ /* output column values */
38 for ( j = 0; j <= 2; j++ ) { ; j++ ) {
39 printf( printf( "%d ", a[ i ][ j ] ); , a[ i ][ j ] );
40 } } /* end inner for */ /* end inner for */
41
42 printf( printf( ""\\\n"n" ); /* start new line of output */ /* start new line of output */
Trang 7– 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 ụ : my array [ 3 ] )
13
void modifyArray( int b[], int arraySize );
– 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 &
int a[10], n = 10;
modifyArray( a, n); // không s ử d ụ ng &a
Trang 8array = 0012FF78
&array[0] = 0012FF78
&array = 0012FF78
1 /* Fig 6.12: fig06_12.c/* Fig 6.12: fig06_12.c
2 The name of an array is the same as &array[ 0 ] */The name of an array is the same as &array[ 0 ] */
3 #include <stdio.h> <stdio.h>
4
5 /* function main begins program execution *//* function main begins program execution */
6 int main() main()
16 } /* end /* end main */main */main */
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.13: fig06_13.c/* Fig 6.13: fig06_13.c
2 Passing arrays and individual array elements to functions */ Passing arrays and individual array elements to functions */
3 #include <stdio.h> <stdio.h>
4 #define SIZE 5 SIZE 5
5
6 /* function prototypes *//* function prototypes */
7 void modifyArray( int b[], int size ); size );
8 void modifyElement( modifyElement( int e ); e );
9
10 /* function main begins program execution *//* function main begins program execution */
11 int main() main()
12 {{
13 int a[ SIZE ] = { 0, 1, 2, 3, 4 }; /* initialize a *//* initialize a */
14 int i; /* counter *//* counter */
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ị)
Trang 9fig06_13.c (Part 2 of 3)
26 /* pass array a to modifyArray by reference *//* pass array a to modifyArray by reference */
27 modifyArray( a, modifyArray( a, SIZE ); );
28 29 printf( "The values of the modified array are:"The values of the modified array are:\\\n"n" ); ); 30 31 /* output modified array *//* output modified array */ 32 for ( i = 0; i < SIZESIZE; i++ ) {; i++ ) { 33 printf( "%3d", a[ i ] ); , a[ i ] ); 34 } /* end for */ /* end for */ 35 36 /* output value of a[ 3 ] *//* output value of a[ 3 ] */ 37 printf( ""\\\nnn\\\nnn\\\nEffects of passing array element "nEffects of passing array element "nEffects of passing array element " 38 "by value:"by value:\\\nnn\\\nThe value of a[3] is %dnThe value of a[3] is %dnThe value of a[3] is %d\\\n"n", a[ 3 ] ); ] ); 39
40 modifyElement( a[ modifyElement( a[ 3 ] ); /* pass array element a[ 3 ] by value *//* pass array element a[ 3 ] by value */ 41 42 /* output value of a[ 3 ] *//* output value of a[ 3 ] */ 43 printf( "The value of a[ 3 ] is %d"The value of a[ 3 ] is %d\\\n"n", a[ 3 ] ); ] ); 44
45 return ; /* indicates successful termination *//* indicates successful termination */ 46 47 } /* end main *//* end main */ 48 49 /* in function modifyArray, "b" points to the original array "a" 50 in memory */in memory */
51 void modifyArray( int b[], int size ) size )
52 { {
53 int j; /* counter *//* counter */
54
55 /* multiply each array element by 2 *//* multiply each array element by 2 */
56 for ( j = 0; j < size; j++ ) { ; j++ ) {
57 b[ j ] *= b[ j ] *= 2;
58 } } /* end for *//* end for */
59
60 } /* end function modifyArray *//* end function modifyArray */
61 62 /* in function modifyElement, "e" is a local copy of array element /* in function modifyElement, "e" is a local copy of array element 63 a[ 3 ] passed from main */a[ 3 ] passed from main */
64 void modifyElement( int e ) e )
65 { {
66 /* multiply parameter by 2 *//* multiply parameter by 2 */
67 printf( printf( "Value in m"Value in modifyElement is %dodifyElement is %dodifyElement is %d\\\n"n", e *= 2 ); );
68 } /* end function modifyElement *//* 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
Trang 10Effects of passing entire array by reference:
The values of the original array are:
0 1 2 3 4
The values of the modified array are:
0 2 4 6 8
Effects of passing array element by value:
The value of a[3] is 6
Value in
Value in modifyElementmodifyElementmodifyElement is 12is 12
The value of a[ 3 ] is 6
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.
Trang 11char string1[ ] = { 'f', 'i', 'r', 's', 't', '\0' };
1 /* Fig 6.10: fig06_10.c /* Fig 6.10: fig06_10.c
2 Treating character arrays as strings */ Treating character arrays as strings */
3 #include <stdio.h> <stdio.h>
4
5 /* function main begins program execution */ /* function main begins program execution */
6 int main() main()
7 { {
8 char string1[ 20 ]; /* reserves 20 characters */ /* reserves 20 characters */ */
9 char string2[] = "string literal" ; /* reserves 15 characters */ /* reserves 15 characters */
10 int i; /* counter */ /* counter */
11
12 /* read string from user into array string2 */ /* read string from user into array string2 */
13 printf( "Enter a string: " ); );
14 scanf( scanf( "%s" , , string1 ); string1 ); string1 );
15
16 /* output strings */ /* output strings */
17 printf( printf( "string1 is: %s\ "string1 is: %s \ \nstring2 is: %s nstring2 is: %s nstring2 is: %s\ \ \n" n" n"
18 "string1 with spaces between characters is:\ "string1 with spaces between characters is: \ \n" n" , ,
19 string1, string2 ); string1, string2 ); string1, string2 );
20
21 /* output characters until null character is reached */ /* output characters until null character is reached */
22 for ( i = 0 ; string1[ i ] != ' '\ \ \0' 0' ; i++ ) { ; i++ ) {
23 printf( printf( "%c " , string1[ i ] ); , string1[ i ] );
24 } } /* end for */ /* end for */
25
Trang 12Khai 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";
• 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 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).
Trang 13Th ư vi
Prototype Description
int isdigit( int c );
Returns true if c is a digit and false otherwise
int isalpha( int c );
Returns true if c is a letter and false otherwise
int isalnum( int c );
Returns true if c is a digit or a letter and false otherwise
int isxdigit( int c );
Returns true if c is a hexadecimal digit character and false otherwise
int islower( int c );
Returns true if c is a lowercase letter and false otherwise
int isupper( int c );
Returns true if c is an uppercase letter; false otherwise
int tolower( int c );
If c is an uppercase letter, tolower returns c as a lowercase letter Otherwise, tolower
returns the argument unchanged
int toupper( int c );
If c is a lowercase letter, toupper returns c as an uppercase letter Otherwise, toupper
returns the argument unchanged
int isspace( int c );
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
int iscntrl( int c );
Returns true if c is a control character and false otherwise
int ispunct( int c );
Returns true if c is a printing character other than a space, a digit, or a letter and false
otherwise
int isprint( int c );
Returns true value if c is a printing character including space (' ') and false otherwise
int isgraph( int c );
Returns true if c is a printing character other than space (' ') and false otherwise
25
• Trong <stdlib.h> ( th ư vi ệ n chu ẩ n)
và s ố th ự c (float)
double atof( const char *nPtr ); Converts the string nPtr to double
int atoi( const char *nPtr ); Converts the string nPtr to int
long atol( const char *nPtr ); Converts the string nPtr to long int
double strtod( const char *nPtr, char
long strtol( const char *nPtr, char
**endPtr, int base ); Converts the string nPtr to long.
unsigned long strtoul( const char
*nPtr, char **endPtr, int base ); Converts the string nPtr to unsigned long.
Trang 14Các hàm th ư vi ệ n I/O chu ẩ n <stdio.h>
int getchar( void ); Inputs the next character from the standard input and
re-turns it as an integer char *gets( char *s ); 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
int putchar( int c ); Prints the character stored in c
int puts( const char *s ); Prints the string s followed by a newline character
int sprintf( char *s, const
char *format, ); Equivalent to printf , except the output is stored in the
array s instead of printing it on the screen
int sscanf( char *s, const
char *format, ); Equivalent to scanf , except the input is read from the array
s instead of reading it from the keyboard
Trang 15Cá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,
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
Trang 16void *memcpy( void
int memcmp( const
void *s1, const void
*s2, size_t n );
Compares the first n characters of the objects pointed to by s1 and s2 The function returns 0 , less than 0 or greater than 0 if s1 is equal to, less than or greater than s2
void *memchr( const
void *s, int c,
size_t n );
Locates the first occurrence of c (converted to unsigned char ) in the first n characters of the object pointed to by s If c is found, a pointer
to c in the object is returned Otherwise, NULL is returned
void *memset( void
1 /* Fig 7.10: fig07_10.c /* Fig 7.10: fig07_10.c
2 Converting lowercase letters to uppercase letters Converting lowercase letters to uppercase letters
3 using a non using a non- - -constant pointer to non constant pointer to non constant pointer to non- - -constant data */ constant data */ constant data */
4
5 #include <stdio.h> <stdio.h>
6 #include <ctype.h> <ctype.h>
Trang 1722 /* convert string to uppercase letters */ /* convert string to uppercase letters */
23 void convertToUppercase( char *sPtr ) *sPtr ) )
24 { {
25 while ( ( *sPtr != *sPtr != ' '\ \ \0' 0' ) { /* current character is not '\ /* current character is not ' \ \0' */ 0' */
26
27 if ( ( islower( *sPtr ) islower( *sPtr ) islower( *sPtr ) ) { ) { /* if character is lowercase, */ /* if character is lowercase, */
28 *sPtr = toupper( *sPtr ); *sPtr = toupper( *sPtr ); *sPtr = toupper( *sPtr ); /* convert to uppercase */ /* convert to uppercase */
29 } /* end if */ /* end if */
30
31 ++sPtr; ++sPtr; ++sPtr; /* move sPtr to the next character */ /* move sPtr to the next character */
32 } /* end while */ /* end while */
33
34 } /* end function convertToUppercase */ /* end function convertToUppercase */
The string before conversion is: characters and $32.98
The string after conversion is: CHARACTERS AND $32.98
33
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.
Trang 18Cá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
• Các string đượ c l ư u tr ữ là m ả ng suit
• 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 ỳ
suit[3]
suit[2]
suit[1]
Trang 191 /* Fig 7.16: fig07_16.c/* Fig 7.16: fig07_16.c
2 Sizeof operator when used on an array nameSizeof operator when used on an array name
3 returns the number of bytes in the array */returns the number of bytes in the array */
4 #include <stdio.h> <stdio.h>
12 printf( printf( "The number of bytes in the array is %d""The number of bytes in the array is %d"
13 ""\\\nThe number of bytes returned by getSize is %dnThe number of bytes returned by getSize is %dnThe number of bytes returned by getSize is %d\\\n"n",,
14 sizeof( array ), getSize( array ) ); ( array ), getSize( array ) );
20 /* return size of ptr *//* return size of ptr */
21 size_t getSize( float *ptr *ptr ) ) )
22 {{
23 return sizeof( ptr );( ptr );
24
25 } /* end function getSize *//* 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/* Fig 7.17: fig07_17.c
2 Demonstrating the sizeof operator */Demonstrating the sizeof operator */
3 #include <stdio.h> <stdio.h>
4
5 int main() main()
6 { {
7 char c; /* define c *//* define c */
8 short s; /* define s *//* define s */
9 int i; /* define i/* define i */ */ */
10 long l; /* define l *//* define l */
11 float f; /* define f *//* define f */
12 double d; /* define d *//* define d */
13 long double ld; /* define ld *//* define ld */
14 int array[ 20 ]; /* initialize array *//* initialize array */
15 int *ptr = array; /* cre/* create pointer to array */ate pointer to array */ate pointer to array */
16
17 printf( " sizeof c = %d" sizeof c = %d\\\tsizeof(char) = %d"tsizeof(char) = %d"
18 ""\\\n sizeof s = %dn sizeof s = %dn sizeof s = %d\\\tsizeof(short) = %d"tsizeof(short) = %d"
19 ""\\\n sizeof i = %dn sizeof i = %dn sizeof i = %d\\\tsizeof(int) = %d"tsizeof(int) = %d"
20 ""\\\n sizeof l = %dn sizeof l = %dn sizeof l = %d\\\tttsizeof(long) = %d"sizeof(long) = %d"
21 ""\\\n sizeof f = %dn sizeof f = %dn sizeof f = %d\\\tsizeof(float) = %d"tsizeof(float) = %d"
22 ""\\\n sizeof d = %dn sizeof d = %dn sizeof d = %d\\\tsizeof(double) = %d"tsizeof(double) = %d"
23 ""\\\n sizeof ld = %dn sizeof ld = %dn sizeof ld = %d\\\tsizeof(long double) = %d"tsizeof(long double) = %d"
24 ""\\\n sizeof array = %dn sizeof array = %dn sizeof array = %d""
25 ""\\\n sizeof ptr = %dn sizeof ptr = %dn sizeof ptr = %d\\\n"n", ,