Home > OS >  C Trying to pass arrays to functions
C Trying to pass arrays to functions

Time:11-01

I am trying to make this code work on Visual Studio 2022, but it tells me that after the second void printArray(int theArray\[\], int sizeOfArray) it expected a ;. I am doing this code based on https://youtu.be/VnZbghMhfOY. How can I fix this?

Here is the code I have:

#include <iostream>
using namespace std;

void printArray(int theArray[], int sizeOfArray);

int main()
{
    int bucky[3] = {20, 54, 675};
    int jessica[6] = {54, 24, 7, 8, 9, 99};

    printArray(bucky, 3);

    void printArray(int theArray[], int sizeOfArray)
    {
        for (int x = 0; x < sizeOfArray; x  ){
            cout << theArray[x] << endl;
        }
    }
}

I tried to change the code order but that only made it worse, the error saying ; is apparently useless and the whole thing breaks apart if I put it there.

CodePudding user response:

You should take the implementation of the function "printArray" out of the main.

#include <iostream>
using namespace std;

void printArray(int theArray[], int sizeOfArray);

int main()
{

    int bucky[3] = {20, 54, 675};
    int jessica[6] = {54, 24, 7, 8, 9, 99};

    printArray(bucky, 3);
    return 0;
}
void printArray(int theArray[], int sizeOfArray)
{
    for (int x = 0; x < sizeOfArray; x  ){
        cout << theArray[x] << endl;
    }
}

CodePudding user response:

C doesn't have nested functions. You need:

#include <iostream>
using namespace std;

void printArray(int theArray[], int sizeOfArray);

int main()
{

    int bucky[3] = {20, 54, 675};
    int jessica[6] = {54, 24, 7, 8, 9, 99};

    printArray(bucky, 3);

}

void printArray(int theArray[], int sizeOfArray)
{

    for (int x = 0; x < sizeOfArray; x  )
    {
         cout << theArray[x] << endl;
    }
}
  •  Tags:  
  • c
  • Related