Summary

1) An array is an ordered collection of variables of the same data type

2) If the size of the array element is not given, the compiler will automatically infer the size of the array based on the number of array elements; Uninitialized elements in the array are automatically initialized to 0.

3) The essence of an array is a contiguous memory, which is used to store the elements of an array; The sizeof the array can be obtained by sizeof, in bytes; Sizeof (arrName). Array size: sizeof(arrName)/sizeof(arrName[0])

4) Array type is determined by element type and number of elements, expressed as type [N]

5) The essence of a multidimensional array is still a one-dimensional array. Each element in an array is an array

6) The essence of a string is an array of characters

7) C language on strings or arrays of characters, must pay attention to the 0 element (‘\0’ terminator); If you use character arrays to simulate string variables, be sure to end the last element with the terminator ‘\0’

StrLen: all characters up to the terminator ‘\0’; StrSize: includes all characters of ‘\0’. StrSize = strLen + 1;

9) char strcpy(char DST, const char * SRC); Note that the second argument to strcpy must be a string

1. One-dimensional arrays

1.1 The concept of arrays

An array is an ordered collection of variables of the same data type.

  • The array as a whole needs a valid name (An array of)
  • In the arrayvariableNo independent naming, just the number in the array
  • The number of variables in the array is fixed (Array size fixed)

1.2 Definition of Arrays

Type Name[size];

int arr[10]; / / define arrays / / named arr (variable) for a total of 10 elements / / each element type to int

1.3 Access to Arrays

  • throughArray name [subscript]The way to access arrays
  • An array is an ordered set of elements with a fixed index
  • Array elements are always indexed at 0 (you can use variables as subscripts)
int arr1[3]; arr1[-1] = 0; Arr1 [0] = 1; arr1[0] = 1; arr1[0] = 1; // ok arr1[3] = 4; // error: there are three elements in the array. The last element has index 2, so the index 3 is out of bounds

Note:

  • onlyintegerTo access an array element as a subscript
  • The subscript crossing the lineIt was a very serious mistake
  • The subscript is out of boundsSerious consequencesMaybe not immediately

1.4 Array initialization

Type Name[N] = {v0, v1… , vN-1}; Initialize the elements in the array to V0, V1…

int main() { int arr[5] = {2, 4, 6, 8, 10}; Int I = 0; int I = 0; for(i=0; i<5; i++) { printf("arr[%d] = %d\n", i, arr[i]); } return 0; }

Array initialization tips:

  • Type Name[] = {v0, v1,…. }; // The compiler automatically determines the size of the array based on the number of initial values
  • Initializes some array elements to 0

    /S<N, default to 0 for elements without an initial value specified

    type Name[N] = {v0, v1, … , vS}; // The first element is given an initial value, and the last element is 0
  • Initialize all array elements to 0

    type Name[N] = {0}; // Same as the previous point, the first element is given a 0, and everything else is given a 0

1.5 Array memory distribution

At the bottom of the computer is a contiguous piece of memory used to store the elements of an array

type Name[n] = {v0, v1, …. }; Number of elements in the array: sizeof(Name)/sizeof(Name[0])

  • The array name is oneThe right value, you canConsider a constant pointer
  • Can only useInteger constantArrays are defined because memory is allocated at compile time
  • Can only usePlastic valueAccesses array elements as subscripts

1.6 Array Type

  • Array types are composed ofThe element typeandThe array sizeJoint decision
  • An array type can be represented astype [N]
int a[10] = {0}; // arrType: int [10] float b[5] = {0}; // arrType: float [5] int c[10]; // arrType: int [10] int i = 0; for(i=0; i<10; i++) c[i] = a[i]; // Assign an array of the same type.

2. Two-dimensional arrays and multidimensional arrays

2.1 Two-dimensional Arrays

The elements of an array can be variables or other array elements (such as arrays, Pointers, functions, etc.). When the elements of an array are another array, a multidimensional array is formed. Type Name[N1][N2]; Type Name[N1][N2]; A two-dimensional array can be thought of as a mathematical matrix (N1 row and N2 column matrix).

Note: the essence of a two-dimensional array is still a one-dimensional array, that is, each element of an array is an array

int a[3][4]; // int [4] (a[1])[2] = 2; // int [2] = 2; // Assign a[2][3] = 2; // Assign a[3][0] to the third variable in the second array; // error, index out of bound

Initialization of a two-dimensional array:

    // 1 2 0
    // 4 5 0
    int a[2][3] = {{1, 2}, {4, 5}};

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

    // 0 0 0
    // 0 0 0
    int a[2][3] = {0};

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

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

Note:

  • A two-dimensional array can, and only can, allow the compiler to automatically size the first dimension
  • The second dimension size must be displayed given, that is:The type of the array element must be correct and valid

    A one-dimensional array has a type of: type [size]. The size compiler for a one-dimensional array can infer that, but the type must be determined. For a two dimensional arraytype [size1][size2]Type [size2] must be specified, so the size of the second dimension must be determined.
  • The method of automatic size determination of the first dimension :(the number of initial values divided by the size of the second dimension) round up

    int a[][3] = {1, 2, 3, 4}; int s1 = sizeof(a) / sizeof(a[0]); // s1 = 2 int i = 0; int j = 0; for(i=0; i<s1; i++) { for(j=0; j<3; j++) { printf("a[%d][%d] = %d\n", i, j, a[i][j]); }}

Problem: output matrix transpose

int a[3][3] = {1, 2, 3, 4}; int i = 0; int j = 0; int arr[3][3] = {0}; / / transpose the for (I = 0; i<3; i++) { for(j=0; j<3; j++) { if(i == j) arr[i][j] = a[i][j]; Else {arr[j][I] = a[I][j]; }}}}

2.2 Multidimensional Arrays

Definition of a three-dimensional array: An array, each element of which is a two-dimensional array

  • Grammar:type name[n1][n2][n3];

Four – dimensional array definition: an array, each element is a three – dimensional array

  • Grammar:type name[n1][n2][n3][n4];

And so on.

3. Strings and character arrays

3.1 Character Arrays

A character array is a special ordered set of integers (an ordered set of characters). Each element in the character array is a variable of type CHAR, a visual character

  • 1 byte per integer (-128-127)
  • You can useCharacter literalInitializes and assigns the array elements
  • Commonly used to store readable text information
char a[] = {97, 98, 99}; Char b[] = {'d', '.', 't', '.'}; char b[] = {'d', '.', 't', '.'}; Int I = 0; int I = 0; for(i=0; i<sizeof(a); i++) printf("%c ", a[i]); // a b c printf("\n"); for(i=0; i<sizeof(b); i++) printf("%c ", b[i]); // d . t .

3.2 the string

2. An ordered set of characters enclosed in double quotes, as in “hello” in C:

  1. There is noDedicated string type
  2. Only throughA character arrayTo simulate a string variable
  3. There areString literal, but only asconstantuse

Therefore:

  • String variable: Use an array of characters to simulate
  • String constant: An ordered character set enclosed in double quotes

The 0 element in the string:

  • The integer 0In the string0 elements
  • The character corresponding to the 0 element is '\0'(escape character), escaping the original character meaning using the backslash ‘\’, the ‘0’ character was originally corresponding to a decimal integer value of 48, after escaping, ‘\0’ represents the decimal integer 0
  • ‘0’ differs from ‘\0’ in that the character ‘0’ is a non-0 value and corresponds to the decimal integer 48

    printf("%d\n", '0'); // 48 printf("%d\n", '\0'); / / 0

3.2.1 “String Variables” : character arrays

  • C language by character arrayssimulationString variable
  • When a 0 element is present in a character array, it is treated as a stringTo use the
  • The ‘\0’ in the character array indicates the end of a string
  • An element in a character array is not necessarily an element in a string

    char ss[] = {'c', 'c', '\0', 'j'}; // The string 'j' is in the string array 'ss', but is not in the string
  • A character arrayIt can be initialized with a string constant
  • A character arrayNot necessarilyIs a string (if it contains the 0 element)'\ 0');
  • A string must be an array of characters

    char dt[] = "abcd"; char name[] = {"efg"}; Int ds = sizeof(dt); int ds = sizeof(dt); // 5 int ns = sizeof(name); // 4 printf("dt = %s\n", dt); // abcd printf("ds = %d\n", ds); // 5 printf("name = %s\n", name); // efg printf("ns = %d\n", ns); / / 4

3.2.2 String manipulation

C language “string variable” does not exist operation operation! But there is a string “toolkit”, String.h, that provides string manipulation tools, which are essentially string-related operations.

  • Strlen (s) -> fetches the stringThe length of the
  • STRCPT (s1, s2) -> copies a character from s2 into s1,s1 = s2
  • Strcat (s1, s2) -> appends s2 to s1,s1 = s1 + s2
  • STRCMP (s1, s2) -> compares s1 and s2 equal, equal to 0

    Int main() {char s[10] = "abcd"; #include <stdio.h>; #include <string.h>; #include <string.h>; int size = sizeof(s); int len = strlen(s); printf("size = %d\n", size); // 10 printf("len = %d\n", len); // 4 char in[16] = {0}; printf("Input a string: "); scanf("%s", in); Printf ("%s\n", in); printf("%s\n", in); }

When assigning a string using the String Tool:

  • You must ensure that the array of characters assigned to the value is large enough (to avoid overstepping the bounds)
  • You must ensure that the assigned string is valid (there is 0 element in the character array)

3.2.3 String exercises

  • Not:

    char r1[1] = {1}; int i=0, e=0; for(i=0; i<strlen("abcd"); i++) { e = "abcd"[i]; // The string is essentially an array of characters: char anonymous[5] = "abcd"; // "abcd"[I] is equivalent to anonymous[I] // To the following array and pointer analysis: *(p+ I)<==>p[I] printf("%d ", e); *(p+ I)<==>p[I]; // 97 98 99 100 } strcat(r1, "abcd"); // error, r1 has no 0 element, not a string. Printf ("r1 = %s\n", r1); printf("r1 = %s\n", r1); // undefined char r2[10] = ""; "Strcat (R2, "abcd");" strcat(R2, "abcd"); // append "abcd" to r1 printf(" R2 = %s\n", R2); // abcd
  • Demo2:

    char r[2] = {'a', 'b', 0}; Warning printf("sizeof(r) = %d\n", sizeof(r)); Warning printf("sizeof(r) = %d\n", sizeof(r)); / / 2
  • Demo3:

    What is the length of // s? char s[10] = "\n\\\r"; Printf ("strlen(s) = %d\n", strlen(s)) printf("strlen(s) = %d\n", strlen(s)); // 3, \n is a newline character; \\ is a backslash '\'; \r is a carriage return // If the sizeof s is asked, then sizeof(s) = 10;
  • Demo4:

    Char str1[] = {"string"}; char str1[] = {"string"; char str2[6] = {0}; char str3[8]; A. strcpy(str1, "Delphi"); Strcpy (str1, str3); strcpy(str1, str3); strcpy(str1, str3); strcpy(str1, str3); strcpy(str1, str3); STRCPT (str2, str1); STRCPT (str2, str1); STRCPT (str2, str1); STRCPT (str2, str1); STRCPT (str2, str1); Strcpy (str3, str1); strcpy(str3, str1); strcpy(str3, str1); strcpy(str3, str1); strcpy(str3, str1); strcpy(str3, str1); // OK, the string is assigned to the character array
  • Demo5:

    // Demo to remove '\0' char s[] = {"abcd\0ef\0gh"}; int len = sizeof(s) / sizeof(s[0]); int i = 0; while(i < len) { if(s[i] == 0) { int j = 0; for(j=i+1; j<len; j++) { s[j-1] = s[j]; } len--; } else { i++; } } printf("%s\n", s);

This paper is summarized from the “C Language Introduction Course” by Tang Zuolin, teacher of “Ditai Software College”. If there are mistakes or omissions, please correct.