There are some issues.
(有一些问题。)
1) Arrays in C++ are indexed from 0, not from 1. That means that when you have an array of 30 elements, allowed indices are from 0 to 29. But in your loop var
iterates from 1 to 30, so the last iteration tries to use total_process[30]
when the last 'truly' accessible element is total_process[29]
.
(1)C ++中的数组从0开始索引,而不是从1开始索引。这意味着当您有30个元素的数组时,允许的索引从0到29。但是在循环变量中, var
从1到30进行迭代,因此最后一次迭代尝试当最后一个“真正”可访问元素是total_process[29]
时,使用total_process[30]
total_process[29]
。)
Such errors can be very difficult to debug, as when you write an element out of bounds of your array, you corrupt surrounding memory, so you can change some other variable in that way. (这样的错误很难调试,因为当您在数组的边界之外写入元素时,会破坏周围的内存,因此您可以通过这种方式更改其他变量。)
To fix this, either iterate with for (var = 0; var < limit; var++)
, or use var - 1
index like this: total_process[var - 1]
. (要解决此问题,请使用for (var = 0; var < limit; var++)
进行迭代,或使用var - 1
索引,例如: total_process[var - 1]
。)
2) Variables and arrays of primitive types such as int
are left uninitialized by default, and you shouldn't access such uninitialized variables.
(2)默认情况下,原始类型(例如int
)的变量和数组未初始化,并且您不应该访问此类未初始化的变量。)
Always make sure that when you use some variable it already has some assigned value. (始终确保使用某些变量时,该变量已具有一些分配的值。)
You can initialize your array with zeros like int arr[30] = {0};
(您可以使用零初始化数组,例如int arr[30] = {0};
)
, int arr[30] = {}
or int arr[30]{}
. (, int arr[30] = {}
或int arr[30]{}
。)
Also be careful and don't get confused with the first way to initialize an array:
(同样要小心,不要与初始化数组的第一种方法混淆:)
int arr[30] = {1};
This doesn't initialize all the elements with 1, but just initializes arr[0]
with 1 and all the other elements with 0. It works so because you can do this:
(这不会用1初始化所有元素,而只是用1初始化arr[0]
以及用arr[0]
初始化所有其他元素。之所以起作用是因为您可以这样做:)
int arr[30] = {1, 2, 3, 4, 5}; // all other will be 0
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…