Moät soá kieán thöùc cô sôû veà laäp trình baèng ngoân ngöõ C

Phaâàn tröôùc | Muïc luïc | Phaâàn sau

XII. Cô sôû veà maûng (arrays)

Noäi dung:

Vôùi phaàn naøy ta laøm quen vôùi caùc khaùi nieäm veà maûng sau:

 

Maûng moät chieàu

Maûng laø moät taäp hôïp caùc bieán coù cuøng chung kieåu döõ lieäu. Khai baùo nhö sau:

data-type  Array-Name[Array-Size];

Ví duï:

int array_int[8];

Lieät keâ maûng

Sau khi khai baùo maûng, ta coù theå tieáp caän ñeán maûng baèng töøng phaàn töû thoâng qua chæ soá cuûa noù.

Ví duï:

char day[7];

Chæ soá cuûa maûng khai baùo [N]  trong C luoân luoân baét ñaàu töø 0 vaø keát thuùc ôû N-1

Gaùn giaù trò ban ñaàu cho maûng

Ta coù theå gaùn caùc giaù trò ban ñaàu cho töøng phaàn töû

day[0] = `S';
day[1] = `M'; ...

hoaëc taäp theå nhö sau:

int arInteger[5] = {100, 8, 3, 365, 16};

Ví duï:

1:  /* Initializing an array */
2:  #include <stdio.h>
3:
4:  main()
5:  {
6:     int i;
7:     int list_int[10];
8:
9:     for (i=0; i<10; i++){
10:       list_int[i] = i + 1;
11:       printf( "list_int[%d] is initialized with %d.\n", i, list_int[i]);
12:    }
13:    return 0;

14: }  

Keát quaû:

list_int[0] is initialized with 1.
list_int[1] is initialized with 2.
list_int[2] is initialized with 3.
list_int[3] is initialized with 4.
list_int[4] is initialized with 5.
list_int[5] is initialized with 6.
list_int[6] is initialized with 7.
list_int[7] is initialized with 8.
list_int[8] is initialized with 9.
list_int[9] is initialized with 10.

Kích thöôùc maûng

Vôùi khai baùo:

data-type  Array-Name[Array-Size];

ta coù theå tính kích thöôùc maûng trong boä nhôù baèng bieåu thöùc

sizeof(data-type) * Array-Size

hoaëc:

sizeof(Array-Name)

Ví duï:

1:  /* Total bytes of an array */
2:  #include <stdio.h>
3:
4:  main()
5:  {
6:     int total_byte;
7:     int list_int[10];
8:
9:     total_byte = sizeof (int) * 10;
10:    printf( "The size of int is %d-byte long.\n", sizeof (int));
11:    printf( "The array of 10 ints has total %d bytes.\n", total_byte);
12:    printf( "The address of the first element: 0x%x\n", &list_int[0]);
13:    printf( "The address of the last element:  0x%x\n", &list_int[9]);
14:    return 0;
15: }

Keát quaû:

The size of int is 2-byte long.
The array of 10 ints has total 20 bytes
The address of the first element: 0x1806
The address of the last element:  0x%1818

Maûng vaø con troû

Maûng vaø con troû coù quan heä raát maät thieát trong C. Bieát ñöôïc con troû chæ ñeán phaàn töû ñaàu tieân trong maûng, ta coù theå laáy ñöôïc toaøn boä noäi dung maûng.

char  *ptr_c;
char  list_c[10];
ptr_c = list_c;

Trong ví duï treân, con troû ptr_c chæ ñeán ñòa chæ cuûa phaàn töû ñaàu tieân list_c[0].

Ví duï:

1:  /* Referencing an array with a pointer */
2:  #include <stdio.h>
3:
4:  main()
5:  {
6:     int *ptr_int;
7:     int list_int[10];
8:     int i;
9:
10:    for (i=0; i<10; i++)
11:       list_int[i] = i + 1;
12:    ptr_int = list_int;
13:    printf( "The start address of the array: 0x%p\n", ptr_int);
14:    printf( "The value of the first element: %d\n", *ptr_int);
15:    ptr_int = &list_int[0];
16:    printf( "The address of the first element: 0x%p\n", ptr_int);
17:    printf( "The value of the first element: %d\n", *ptr_int);
18:    return 0;
19: }

Keát quaû:

The start address of the array: 0x1802
The value of the first element: 1
The address of the first element: 0x1802
The value of the first element: 1

Chuoãi kyù töï (String)

Chuoãi kyù töï laø moät maûng kyù töï vôùi kyù töï cuoái cuøng laø kyù töï troáng (null - \0).

Kyù töï troáng (\0)  trong C ñöôïc hieåu laø FALSE, vaø caùc kyù töï khaùc null ñöôïc hieåu laø TRUE. Coù theå söû duïng ñieàu ñoù ñeà xuaát kyù töï trong ñoïan leänh sau:

    char str2[] = "Another string constant";
    int i;
    /* print out str2 */
    /* print out str2 */
    for (i=0; str2[i]; i++)
       printf("%c", str2[i]);

Ví duï:

1:  /* Printing out an array of characters */
2:  #include <stdio.h>
3:
4:  main()
5:  {
6:     char array_ch[7] = {`H', `e', `l', `l', `o', `!', `\0'};
7:     int i;
8:
9:     for (i=0; i<7; i++)
10:       printf("array_ch[%d] contains: %c\n", i, array_ch[i]);
11:    /*---  method I ---*/
12:    printf( "Put all elements together(Method I):\n");
13:    for (i=0; i<7; i++)
14:       printf("%c", array_ch[i]);
15:    /*---  method II ---*/
16:    printf( "\nPut all elements together(Method II):\n");
17:    printf( "%s\n", array_ch);
18:
19:    return 0;
20: }

Keát quaû:

array_ch[0] contains: H
array_ch[1] contains: e
array_ch[2] contains: l
array_ch[3] contains: l
array_ch[4] contains: o
array_ch[5] contains: !
array_ch[6] contains:
Put all elements together(Method I):
Hello!
Put all elements together(Method II):
Hello!

Maûng nhieàu chieàu

data-type  Array-Name[Array-Size1][Array-Size2]. . .
[Array-SizeN];

vôùi N laø soá nguyeân döông.

Ta coù theå gaùn giaù trò ban ñaàu cho maûng nhieàu chieàu nhö sau:

array_int[0][0] = 1;
array_int[0][1] = 2;
array_int[0][2] = 3;
array_int[1][0] = 4;
array_int[1][1] = 5;
array_int[1][2] = 6;

hoaëc

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

hoaëc

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

Ví duï:

1:  /* Printing out a 2-D array */
2:  #include <stdio.h>
3:
4:  main()
5:  {
6:     int two_dim[3][5] = {1, 2, 3, 4, 5,
7:                          10, 20, 30, 40, 50,
8:                          100, 200, 300, 400, 500};
9:     int i, j;
10:
11:    for (i=0; i<3; i++){
12:       printf("\n");
13:       for (j=0; j<5; j++)
14:          printf("%6d", two_dim[i][j]);
15:    }
16:    return 0;
17: }

Keát quaû:

     1     2     3     4     5
     10    20    30    40    50
     100   200   300   400   500

Maûng kích thöôùc khoâng ñònh tröôùc

Khaùc vôùi moät soá ngoân ngöõ khaùc, ngoân ngöõ C coù theå tính töï ñoäng kích thöôùc cuûa moät maûng khoâng ñònh tröôùc, ví duï, khi ta coù

int  list_int[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90};

boä bieân dòch seõ taïo ra maûng ñuû lôùn ñeå chöùa taát caû caùc phaàn töû.

Moät ví duï khaùc veà maûng nhieàu chieàu khoâng ñònh tröôùc:

char list_ch[][2] = {
         `a', `A',
         `b', `B',
         `c', `C',
         `d', `D',
         `e', `E',
         `f', `F',
         `g', `G'};

Ví duï:

1:  /* Initializing unsized arrays */
2:  #include <stdio.h>
3:
4:  main()
5:  {
6:     char array_ch[] = {`C', ` `,
7:                        `i', `s', ` `,
8:                        `p', `o', `w', `e', `r',
9:                        `f', `u', `l', `!', `\0'};
10:    int list_int[][3] = {
11:           1, 1, 1,
12:           2, 2, 8,
13:           3, 9, 27,
14:           4, 16, 64,
15:           5, 25, 125,
16:           6, 36, 216,
17:           7, 49, 343};
18:
19:    printf("The size of array_ch[] is %d bytes.\n", sizeof (array_ch));
20:    printf("The size of list_int[][3] is %d bytes.\n", sizeof (list_int));
21:    return 0;
22: }

Keát quaû:

The size of array_ch[] is 15 bytes.
The size of list_int[][3] is 42 bytes.

Baøi taäp

  1. Vôùi int data[3], coù gì sai trong caùch gaùn giaù trò sau ñaây?
data[1] = 1;
data[2] = 2;
data[3] = 3;
  1. Caùc maûng sau ñaây coù kích thöôùc lôùn bao nhieâu?
  2. Coù gì sai trong khai baùo sau?
char list_ch[][] = {
         `A', `a',
         `B', `b',
         `C', `c',
         `D', `d',
         `E', `e'};
 

Phaâàn tröôùc | Muïc luïc | Phaâàn sau