MMGameslogo  MMGames
TwitterSharebutton  FacebookSharebutton   
learn through sufferingC Language
learn through sufferingC Language

Arrays

Initial assignment
Arrays, like variables previously discussed, can also be declared and initialized at the same time.
Array initialization is performed as follows:

Array initialization
型名 array名[要素数]={0番のnumerics,1番のnumerics,2番のnumerics,・・・};

"List numbers separated by commas within curly braces."
You don't need to specify everything, so the number of values should be less than or equal to the number of elements in the array.
"If the number of elements provided is less than the array's size, the remaining elements will be assigned a value of 0."
The following program is an example of initializing and displaying an array.

Source code
#include <stdio.h>

int main(void)
{
    int array[10] = { 42, 79, 13 };

    printf("array[0] = %d\n", array[0]);
    printf("array[1] = %d\n", array[1]);
    printf("array[2] = %d\n", array[2]);
    printf("array[3] = %d\n", array[3]);
    printf("array[4] = %d\n", array[4]);

    return 0;
}

The results of this program's execution are as follows:

Execution results
array[0]= 42
array[1]= 79
array[2]= 13
array[3]= 0
array[4]= 0

If declared this way, you can omit the number of elements.
In that case, an array with the specified number of elements will be allocated.
The following program demonstrates an example of declaring an array without specifying the number of elements.

Source code
#include <stdio.h>

int main(void)
{
    int array[] = { 42, 79, 13 }; /* 要素数が省略されている */

    printf("array[0] = %d\n", array[0]);
    printf("array[1] = %d\n", array[1]);
    printf("array[2] = %d\n", array[2]);

    return 0;
}

This eliminates the need to specify the number of elements and prevents miscounting.
It's better to omit it when initial values can be assigned.

You can only assign values to an array once during its declaration.
For example, the following assignments are not possible.

Invalid assignment
array = { 42, 79, 13 };
array[10] = { 42, 79, 13 };

This way of writing will result in a compilation error.
If you want to assign values after a declaration, you should assign them one by one, even if it's a bit of a hassle.

Possible substitutions
array[0] = 42;
array[1] = 79;
array[2] = 13;

Show all elements.
You can use a for loop to display all elements of an array.
This kind of usage is the greatest advantage of the array.
The following program is an example that displays the number of elements in an array.

Source code
#include <stdio.h>

int main(void)
{
    int array[] = { 42, 79, 13, 75, 19 };
    int i;

    for (i = 0; i < 5; i++) {
        printf("array[%d] = %d\n", i, array[i]);
    }

    return 0;
}

The output of this program is as follows:

Execution results
array[0] = 42
array[1] = 79
array[2] = 13
array[3] = 75
array[4] = 19

The key point of this program is that variables can also be used for the element number in arrays .
By changing the value of a variable, you can directly access different elements.
With regular variables that aren't arrays, you'd need five printf functions to display five elements.
"You need 100 of them to display 100, but with an array, you only need to change the number in the for loop."

"With this, I could easily write a program to display data for 10,000 people."
In addition, you can modify the statement within the loop to assign the same value to all elements.
It's also easy to calculate the average of values assigned to all elements.
Determine the number of elements.
In the previous section, we displayed all the elements of the array using a for loop.
"We specified the number of repetitions as 5 directly, but that means we have to count the number of elements."
With this method, you need to rewrite the for loop every time the number of elements increases.

It's tedious, so I'll automatically determine the number of elements and make it loop.
There isn't a direct method to determine the number of elements, but it can be calculated.

To find the number of elements, determine the size of the entire array and divide it by the size of a single element.
C has the sizeof operator to determine the size of variables and arrays.
The `sizeof` operator is used as follows:

sizeof operator
sizeof(variableやarray名)

While the `sizeof` operator doesn't require parentheses, it's common to include them for better readability.
To calculate the number of elements in the array `array` using this operator, do the following:

Find the number of elements in array.
sizeof(array) / sizeof(array[0])

"We use array[0] because even if the array has a length of 1, the element at index 0 always exists."
If you set it to array[1], it will result in an error when the array length is 1.

The following program is an example of rewriting the previous program in this way.

Source code
#include <stdio.h>

int main(void)
{
    int array[] = { 42, 79, 13, 75, 19 };
    int i;

    for (i = 0; i < sizeof(array) / sizeof(array[0]); i++) {
        printf("array[%d] = %d\n", i, array[i]);
    }

    return 0;
}

The results will be the same as last time.
"Changing the number of array elements will automatically display that many."

Store the number of elements in a variable to eliminate redundancy.
In fact, there's some waste in the above program.
なぜならループ1回毎に「sizeof(array) / sizeof(array<0>)」の計算をしているためis.

int array_count = sizeof(array) / sizeof(array<0>);
for (i = 0;i < array_count;i++) {

By storing the number of elements in a variable, you can avoid redundant calculations each time.
まあ、今のパソコンはとても高性能なので、あまり大差ないんですけどね・・・

Array copy
To assign the values of all elements in one array to another array, you use a for loop.

Source code
#include <stdio.h>

int main(void)
{
    int array1[] = { 42, 79, 13, 19, 41 };
    int array2[] = { 1, 2, 3, 4, 5 };
    int i;

    for (i = 0; i < sizeof(array2) / sizeof(array2[0]); i++) {
        printf("array2[%d] = %d\n", i, array2[i]);
    }

    /* array1 の全要素を array2 にcopy */
    for (i = 0; i < sizeof(array2) / sizeof(array2[0]); i++) {
        array2[i] = array1[i];
    }

    for (i = 0; i < sizeof(array2) / sizeof(array2[0]); i++) {
        printf("array2[%d] = %d\n", i, array2[i]);
    }

    return 0;
}

The output of this program is as follows:

Execution results
array2[0] = 1
array2[1] = 2
array2[2] = 3
array2[3] = 4
array2[4] = 5
array2[0] = 42
array2[1] = 79
array2[2] = 13
array2[3] = 19
array2[4] = 41

Looking at the results, it's clear that the values of array1 have been copied to array2.

However, you can also use the memcpy function without using a for loop.
"Note that you need to include the memory.h file with #include to use the memcpy function."

memcpy function
memcpy(copy先array名、copy元array名、array全体のサイズ)

The size of an array depends on its type and the number of elements it contains.
This function is based on the size obtained using the sizeof operator.

To copy all elements of an array, specify the array name with the `sizeof` operator.
The following program is an example of copying an array using the memcpy function.

Source code
#include <memory.h>
#include <stdio.h>

int main(void)
{
    int array1[] = { 42, 79, 13, 19, 41 };
    int array2[] = { 1, 2, 3, 4, 5 };
    int i;

    for (i = 0; i < sizeof(array2) / sizeof(array2[0]); i++) {
        printf("array2[%d] = %d\n", i, array2[i]);
    }

    memcpy(array2, array1, sizeof(array1)); /* array1 の全要素を array2 にcopy */

    for (i = 0; i < sizeof(array2) / sizeof(array2[0]); i++) {
        printf("array2[%d] = %d\n", i, array2[i]);
    }

    return 0;
}

The result will be exactly the same as before.

buffer overflow
In the above, the source array (array1) and the destination array (array2) are the same length.
Therefore, it will be perfectly copied without any overhang.

Unfortunately, the memcpy function doesn't take into account the lengths of the respective arrays.
"It will forcibly copy the entire source array even if it's longer than the destination array."

As a result, a significant portion will be clipped and copied.
As a result, it overwrites unrelated variables or arrays, leading to significant calculation errors.
This is the infamous bug known as a buffer overflow.
Many crashes and freezes in apps and computers are often caused by buffer overflows.
まあ、厳密には、はみ出してcopyされただけの場合はバッファオーバーフローですが・・・

C is a language that is very prone to bugs.
A small programming error can quickly cause the app to crash.
JavaやC#やRustなどのより新しいprogramming言語は、
It is designed to minimize the occurrence of buffer overflows.



About This Site

Learning C language through suffering (Kushi C) is
This is the definitive introduction to the C language.
It systematically explains the basic functions of the C language.
The quality is equal to or higher than commercially available books.

Part 0: Program Overview
  1. What is a program?
Chapter 3: Displaying on the Screen
  1. String Display
  2. newline character
  3. Practice Problem 3
Chapter 4: Displaying and Calculating Numbers
  1. Display of numbers
  2. Basic calculations
  3. Numeric types
  4. Practice Problem 4
Chapter 6: Input from the Keyboard
  1. input function
  2. The fear of input
  3. Practice Problem 6
Chapter 9: Repeating a Fixed Number of Times
  1. Iterative sentence
  2. How Loops Work
  3. Practice Problem 9
Chapter 10: Repeating Without Knowing the Number of Times
  1. Unspecified loop
  2. Input validation
  3. Practice Problem 10
Chapter 13: Handling Multiple Variables at Once
  1. Handling multiple variables collectively.
  2. Arrays
  3. Practice Problem 13
Chapter 19: Dynamic Arrays
  1. Create arrays freely.
  2. Practice Problem 19