-2

i finish writing my code and i am unable to figure out why i am getting an expected ; error

i tried adding the ; where it expects me too but it kicks back other errors instead

here is my code

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;
}

}

anon
  • 15
  • 3
  • 2
    C++ don't support functions within functions (move `expandArray` function outside of `main` function). Having said that: consider learning from a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Algirdas Preidžius Mar 26 '19 at 17:17
  • 1
    You have defined a function inside `main` (which is also a function). You can't do that in `c++`. You can move the whole of `expandArray` outside of main and then call it. Not really clear what you expect this code to do. – super Mar 26 '19 at 17:17
  • 1
    Also for future reference (and this applies to online code help everywhere), if you want people to help with your code, you have to explain to the people helping you what your code is supposed to do, otherwise, you cannot get the best help. – Mode77 Mar 26 '19 at 17:21

1 Answers1

1

C++ doesn't allow nested functions. You can't define a function in your main().

In fact, this is a duplicate of Can we have functions inside functions in C++?

You probably want:

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
}
Jeffrey
  • 11,063
  • 1
  • 21
  • 42