C++ 如何在c+中分配大小+;对于数组?
如果我们用4个元素初始化数组,例如:C++ 如何在c+中分配大小+;对于数组?,c++,C++,如果我们用4个元素初始化数组,例如: int array[4]; 我们可以这样赋值吗,因为它也需要4个值: for(int i=5;i<9;i++){ cin>>array[i]; } for(int i=5;i<9;i++){ cin>>array[i]; for(int i=5;i>array[i]; } 不,您得到的阵列有4个插槽。这些插槽是 array[0] array[1] array[2] array[3] 所以你的代码
int array[4];
我们可以这样赋值吗,因为它也需要4个值:
for(int i=5;i<9;i++){
cin>>array[i];
}
for(int i=5;i<9;i++){
cin>>array[i];
for(int i=5;i>array[i];
}
不,您得到的阵列有4个插槽。这些插槽是
array[0]
array[1]
array[2]
array[3]
所以你的代码是不正确的。它似乎可以工作,但由于所谓的未定义行为,它仍然是错误的,下周它可能会失败
注意:最好在c++中使用std::vector,因为它混淆了两种结构:循环中用于迭代的逻辑和数组的索引 你可以用
for(int i=5;i<9;i++){
...
}
数组上的越界访问具有未定义的行为,这是表示“意外后果”的另一种方式:
inta[4];
int b[4];
对于(int i=5;i
我们是否可以这样分配值,因为它也需要4个值:
for(int i=5;i<9;i++){
cin>>array[i];
}
for(int i=5;i<9;i++){
cin>>array[i];
不,您将访问超出范围的数组。“工作”和“可能导致不可预知的行为和崩溃”通常很难区分。此代码绝对是未定义的行为,并且可以并且将在您最不希望的时候崩溃。@YadvendraKumar它是未定义的行为。它包括“工作”还有其他的行为。cin>>array[i-5];
@YadvendraKumar和大多数新手一样,你对未定义行为(UB)的概念有困难你的程序有UB,因为它是越界数组访问。UB是指它的行为,它是不确定的。C++不表示你的程序不工作,它只是说行为是不确定的,它可以工作,它可能崩溃,它可以做任何事情。显然,最好避免UB.as。我的评论说,它看起来可能有用,但这是UB。@如果你不倾听,就用这种方式编码。最终你会在这里(或其他地方)问“为什么这个代码不起作用”忘记一个:摧毁地球*,以及地球上的所有生物。*如果这是Microsoft编译器的结果,请向用户语音提交一个问题,Microsoft将相应地对其进行优先级排序。
- working
- not working
- random output
- non-random output
- the expected output
- unexpected output
- no output
- any output
- crashing at random
- crashing always
- not crashing
- corruption of data
- different behaviour, when executed on another system
- , when compiled with another compiler
- , on tuesday
- , only when you are not looking
- same behaviour in all of the above cases
- anything else within the power of the computer (hopefully limited by the OS)