[英]Why do i have to initialize an array?
So why do i have to do this "People[city][years] =1000 ;" 那么,为什么我必须这样做“ People [city] [years] = 1000 ;” thing?
事情?
int People[2059][100];
for (int city = 0; city < 2059; city++)
for (int years = 0; years < 100; years++)
People[city][years] = 1000;
You don't have to. 不用了 But then the
People
array will contain indeterminate values, and reading them makes for a program with undefined behavior (I'm assuming that it's a variable with automatic storage duration). 但是,
People
数组将包含不确定的值,读取它们会使程序具有未定义的行为(我假设它是具有自动存储持续时间的变量)。 That's not an overly useful program. 那不是一个有用的程序。
If the array has static storage duration, then it will be zero-initialized. 如果数组具有静态存储持续时间,则它将被初始化为零。 If you are okay with that, you don't have to loop over it and assign values immediately.
如果您对此表示满意,则不必遍历它并立即分配值。
This line: 这行:
People[city][years] = 1000;
initializes the values in your 2D array to 1000
on the stack. 将2D数组中的值初始化为堆栈上的
1000
。 If you don't initialize the numbers in your array, they can be anything. 如果您不初始化数组中的数字,则它们可以是任何数字。
Instead, you can initialize the numbers in People
to 0
: 相反,您可以将
People
的数字初始化为0
:
int People[2059][100] = {{0}}; /* or 1000, if you prefer that */
Using this instead saves you having to loop over the array and assign every value to 0
. 相反,使用此方法可以省去遍历数组并将每个值分配为
0
。 If you decide to insert other numbers, then initializing the array won't be needed. 如果决定插入其他数字,则不需要初始化数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.