我完成了编写代码,无法弄清为什么我得到了期望;错误
我尝试添加;它也期待我,但反而会踢出其他错误
这是我的代码
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;
}
}
答案 0 :(得分:1)
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
}