Brother Jiang takes you to play with C language | 10- C language array

Posted by kat89 on Wed, 02 Feb 2022 01:08:42 +0100

Basic concept of array

  • Array, literally, means a set of data. Yes, array is used to store a set of data

    • In C language, array belongs to construction data type
  • Several nouns of array

    • Array: an ordered collection of data of the same data type
    • Array element: each data that constitutes an array.
    • Subscript of array: index of array element position (starting from 0)
  • Application scenario of array

    • An int type variable can save a person's age. What if you want to save the age of the whole class?
      • The first method is to define many variables of type int to store
      • The second method is to define only an array of int type to store
#include <stdio.h>

int main(int argc, const char * argv[]) {
    /*
    // Requirement: save the scores of 2 people
    int score1 = 99;
    int score2 = 60;
    
    // Requirement: save the scores of the whole class (130 people)
    int score3 = 78;
    int score4 = 68;
    ...
    int score130 = 88;
    */
    // Array: if you need to save a group of data of the same type, you can define an array to save it
    // As long as an array is defined, each small storage space will be given a number inside the array. This number is called the index, and the index starts from 0
    // 1. Define an array that can hold three int types
    int scores[3];
    
    // 2. Store data into the array through the index of the array
    scores[0] = 998;
    scores[1] = 123;
    scores[2] = 567;
   
    // 3. Fetch the stored data from the array through the index of the array
    printf("%i\n", scores[0]);
    printf("%i\n", scores[1]);
    printf("%i\n", scores[2]);
    return 0;
}

Define array

  • Element type array name [number of elements];
// int element type
// ages array name
// [10] Number of elements
int ages[10];

Initialize array

  • Initialize while defining
  • Specify the number of elements and complete initialization
    • The data values in {} are the initial values of each element, and the values are separated by commas
int ages[3] = {4, 6, 9};
  • Do not specify the number of elements, full initialization
    • Determine the number of elements of the array according to the number of elements in braces
int nums[] = {1,2,3,5,6};
  • Specify the number of elements, partial initialization
    • If there is no explicitly initialized element, the system will automatically initialize it to 0
int nums[10] = {1,2};
  • Specify the number of elements, partial initialization
int nums[5] = {[4] = 3,[1] = 2};
  • Partial initialization without specifying the number of elements
int nums[] = {[4] = 3};
  • Define before initialize
int nums[3];
nums[0] = 1;
nums[1] = 2;
nums[2] = 3;
  • What happens without initialization?
    • If there is no initialization after defining the array, the array has values and is a random garbage number. Therefore, if you want to use the array correctly, you should initialize it.
int nums[5];
printf("%d\n", nums[0]);
printf("%d\n", nums[1]);
printf("%d\n", nums[2]);
printf("%d\n", nums[3]);
printf("%d\n", nums[4]);
Output results:
0
0
1606416312
0
1606416414
  • Note:
  • When using an array, you cannot exceed the index range of the array. The index starts from 0 and ends with the number of elements - 1
  • When using an array, do not use uninitialized elements arbitrarily. It may be a random value
  • For an array, you can only initialize multiple values at the same time of definition. You cannot define multiple values first and then initialize them
int ages[3];
ages = {4, 6, 9}; // report errors

Use of arrays

  • Accessed by subscript (index):
// Found element with subscript 0
ages[0]=10;
// Take out the saved value of the element with subscript 2
int a = ages[2];
printf("a = %d", a);

Traversal of array

  • Array traversal: traversal means to view each element of the array in order
    int ages[4] = {19, 22, 33, 13};
    for (int i = 0; i < 4; i++) {
        printf("ages[%d] = %d\n", i, ages[i]);
    }

Array length calculation method

  • Because the number of bytes the array occupies in memory depends on the type of data it stores and the number of data
    • Storage space occupied by array = storage space occupied by an element * number of elements (array length)
  • Therefore, the following method can be used to calculate the length of the array
    Length of array = total bytes occupied by array / bytes occupied by array elements
    int ages[4] = {19, 22, 33, 13};
    int length =  sizeof(ages)/sizeof(int);
    printf("length = %d", length);
Output results: 4

practice

  • Positive order output (traversal) array
    int ages[4] = {19, 22, 33, 13};
    for (int i = 0; i < 4; i++) {
        printf("ages[%d] = %d\n", i, ages[i]);
    }
  • Output (traverse) array in reverse order
    int ages[4] = {19, 22, 33, 13};
    for (int i = 3; i >=0; i--) {
        printf("ages[%d] = %d\n", i, ages[i]);
    }
  • Enter the length of the array from the keyboard, build an array, and then receive numbers from the keyboard through the for loop to initialize the array. And use the for loop output to view

Array internal storage details

  • Storage method:

    • 1) Memory addressing from large to small, from high address to open up a continuous unused memory to the array
    • 2) Allocate space to each element from the position with small address in the allocated continuous storage space
    • 3) The data is stored from the location with the largest address in the storage space allocated by each element
    • 4) Use the array name to point to the address with the smallest storage space
  • Examples

#include <stdio.h>
int main()
{
    int num = 9;
    char cs[] = {'l','n','j'};
    printf("cs = %p\n", &cs);       // cs = 0060FEA9
    printf("cs[0] = %p\n", &cs[0]); // cs[0] = 0060FEA9
    printf("cs[1] = %p\n", &cs[1]); // cs[1] = 0060FEAA
    printf("cs[2] = %p\n", &cs[2]); // cs[2] = 0060FEAB

    int nums[] = {2, 6};
    printf("nums = %p\n", &nums);      // nums = 0060FEA0
    printf("nums[0] = %p\n", &nums[0]);// nums[0] = 0060FEA0
    printf("nums[1] = %p\n", &nums[1]);// nums[1] = 0060FEA4
    
    return 0;
}

  • Note: characters are stored in memory in binary form corresponding to ASCII code value instead of the above form.

Array out of bounds

  • Problems caused by array out of bounds
    • About the wrong object
    • Program crash
    char cs1[2] = {1, 2};
    char cs2[3] = {3, 4, 5};
    cs2[3] = 88; // Note: this sentence accesses memory that does not belong to cs1
    printf("cs1[0] = %d\n", cs1[0] );
Output results: 88

Why does the above output 88 and draw brain compensation according to "details stored inside the array"

Array considerations

  • When defining an array, [] can only write integer constants or expressions that return integer constants
 int ages4['A'] = {19, 22, 33};
 printf("ages4[0] = %d\n", ages4[0]);

  int ages5[5 + 5] = {19, 22, 33};
  printf("ages5[0] = %d\n", ages5[0]);

  int ages5['A' + 5] = {19, 22, 33};
  printf("ages5[0] = %d\n", ages5[0]);
  • Wrong writing
// No number of elements specified, error
int a[];

// Variables cannot be placed in []
int number = 10;
int ages[number]; // The old version of C language specification does not support
printf("%d\n", ages[4]);

int number = 10;
int ages2[number] = {19, 22, 33} // Direct error reporting

// Only one-time (all assignment) initialization can be performed when defining the array
int ages3[5];
ages10 = {19, 22, 33};

// An array with a length of N, the maximum subscript is n-1, and the subscript range is 0~n-1
int ages4[4] = {19, 22, 33}
ages4[8]; // Array subscript out of bounds
  • practice
    • Enter the price of BTC sold on the current day from the keyboard and calculate the total price and average price of BTC sold (for example, 10 bitcoins sold in a day)

Arrays and functions

  • Arrays can be used as function parameters. Arrays can be used as function parameters in two forms:
    • One is to use array elements as arguments
    • One is to use the array name as the formal and actual parameters of the function

Array elements as function parameters

  • The elements of the array are used as function arguments, just as simple variables of the same type are used as arguments. If it is a basic data type, the change of formal parameters will not affect the arguments
void change(int val)// int val = number
{
    val = 55;
}
int main(int argc, const char * argv[])
{
    int ages[3] = {1, 5, 8};
    printf("ages[0] = %d", ages[0]);// 1
    change(ages[0]);
    printf("ages[0] = %d", ages[0]);// 1
}
  • Using array elements as function parameters does not require formal parameters to be array elements

Array name as function parameter

  • In C language, in addition to being the identifier of the variable, the array name also represents the starting address of the array in memory. Therefore, when the array name is used as a function parameter, the actual parameter and formal parameter are not "value transfer", but "address transfer"
  • The parameter array name passes the starting address of the array to the formal parameter array. The two arrays share a memory unit, and the system will no longer allocate storage units for the shape parameter group
  • Since the two arrays share a memory unit, when the formal parameter array is modified, the argument array is modified at the same time
void change2(int array[3])// int array = 0ffd1
{
    array[0] = 88;
}
int main(int argc, const char * argv[])
{
    int ages[3] = {1, 5, 8};
    printf("ages[0] = %d", ages[0]);// 1
    change(ages);
    printf("ages[0] = %d", ages[0]);// 88
}

Notes on using array names as function parameters

  • In the function parameter table, it is allowed not to give the length of the shape parameter group
void change(int array[])
{
    array[0] = 88;
}
  • The types of formal parameter array and argument array must be consistent, otherwise an error will be caused.
void prtArray(double array[3]) // Wrong writing
{
    for (int i = 0; i < 3; i++) {
        printf("array[%d], %f", i, array[i]);
    }
}
int main(int argc, const char * argv[])
{
    int ages[3] = {1, 5, 8};
    prtArray(ages[0]);
}
  • When the array name is used as a function parameter, because it is automatically converted to a pointer type, the number of elements divided by the array cannot be dynamically calculated in the function
void printArray(int array[])
{
    printf("printArray size = %lu\n", sizeof(array)); // 8
    int length = sizeof(array)/ sizeof(int); // 2
    printf("length = %d", length);
}
  • practice:
    • Design a function int arrayMax(int a[], int count) to find out the maximum value of array elements
    • Input three numbers 0-9 from the keyboard, and then output which numbers in 0-9 have not appeared
    • It is required to input 6 numbers from 0 to 9 from the keyboard and output them after sorting

If you think the article is helpful to you, like, collect, pay attention to, comment, and support four times with one button, your support is the driving force for brother Jiang's continuous update.

Supporting video address

Topics: C Algorithm Programmer pointer array