为什么循环在这段代码中只运行一次?
// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n=5;
int a[n];
for(int i=0;i<sizeof(a);i++)
{
cout<<"mohit jain"<<endl;
}
return 0;
}
虽然在代码中循环迭代了五次?
// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a[5];
for(int i=0;i<sizeof(a);i++)
{
cout<<"mohit jain"<<endl;
}
return 0;
}
所以请告诉我为什么它在第一个代码中迭代一次而在第二个代码中迭代五次的正当理由。
最佳答案
考虑改用 const int n = 5
。
默认情况下,C++ 不允许动态大小的数组(在本例中它是动态的,因为 n
是非常量)。它之所以有效,是因为您的编译器在这种情况下使用某种扩展来分配数组,例如gcc 的变量数组。
因此,第一个示例是非标准 C++ 代码,sizeof
返回 1 而不是 5 * sizeof(int)
的原因在于特定于编译器的实现的扩展名。
顺便说一句,第二个循环运行 5 * sizeof(int)
次(在大多数系统上是 20 次),而不是 5 次。
关于c++ - 循环在此代码中仅迭代一次,而在另一代码中它正确迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43138356/