这个问题在这里已有答案:
我完成了我的代码编写,我无法弄清楚为什么我得到了预期;错误
我试着添加;它也期望我,但它会反过来推翻其他错误
这是我的代码
int main() {
int* expandArray(int *arr, int SIZE) { //this is the error line
//dynamically allocate an array twice the size
int *expPtr = new int[2 * SIZE];
//initialize elements of new array
for (int i = 0; i < 2 * SIZE; i++) {
//first add elements of old array
if (i < SIZE) {
*(expPtr + i) = *(arr + i);
}
//all next elements should be 0
else {
*(expPtr + i) = 0;
}
}
return expPtr;
}
}
C ++不允许嵌套函数。您无法在main()中定义函数。
事实上,这是Can we have functions inside functions in C++?的副本
你可能想要:
int* expandArray(int *arr, int SIZE)
{ //this is the error line
//dynamically allocate an array twice the size
int *expPtr = new int[2 * SIZE];
//initialize elements of new array
for (int i = 0; i < 2 * SIZE; i++)
{
//first add elements of old array
if (i < SIZE)
{
*(expPtr + i) = *(arr + i);
}
//all next elements should be 0
else
{
*(expPtr + i) = 0;
}
}
return expPtr;
}
int main()
{
// call expandArray here
}