【发布时间】:2016-02-03 19:57:20
【问题描述】:
#include <iostream>
using namespace std;
/* This code is not working as it does not insert the value of item in the
array instead the value of item is zero. But i have troubleshooted this
problem and figured out that the code works fine if i define "int item" as
constant variable or use int i as global variable instead of defining in the
for loop. so my question is what is the reason behind this malfunctioning or
is there any programming secret i haven't aware of yet*/
int main()
{
int LA[] = {1, 3, 64, 98, 54};
int k = 3;
int n = 5;
int item = 46;
int j = n;
for(int i = 0; i < n; i++)
{
cout << "LA[" << i << "] = " << LA[i] << endl;
}
n++;
for( ; j >= k; j-- )
{
LA[j+1] = LA[j];
}
LA[k] = item;
cout << endl << "After insertion" << endl << endl;
for(int i = 0; i < n; i++)
{
cout << "LA[" << i << "] = " << LA[i] << endl;
}
return 0;
}
【问题讨论】:
-
int LA[]自初始化以来具有固定大小。查找std::vector。请注意,j = 5的LA[j]已经超出范围。 -
请自己调试丑陋的代码(或有
const int n = 5;) -
还有一个更可能的重复“你能在初始化后调整 C++ 数组的大小吗?” stackoverflow.com/questions/756906/…。简短的回答:你不能。如果您需要可调整大小的数组,请使用 std::vector。