Home > OS >  expected primary-expression before 'int' shows up when calling a function. How to fix?
expected primary-expression before 'int' shows up when calling a function. How to fix?

Time:12-02

Trying to call a function, error shows up saying that it requires a primary-expression. How to solve?

Function is all about getting user input and putting it into an array list. This is just a small part of a whole code, I am testing out the parts so I can debug it more easily.

This is the error that shows up:

15 23 C:\Users\asus\Desktop\TERM 2\CS107-8L\tester.cpp [Error] expected primary-expression before 'int'

#include<iostream>
#include<iomanip>

using namespace std;


void getInput(int list[],int dim);


int main()
{

    
    cout<<"enter number: "<<endl;
    getInput(int list[], int dim);

    
}


void getInput(int list[], int dim)
{       
    for(int i = 0; i<20; i  )
    {
        cout<<"loc["<<i<<"] ";
        cin>>list[i];
    }
}

CodePudding user response:

First of all, there's is no list and dim defined in your code.

Second, VLA-arrays are not valid in C . You should use std::vector<int> instead:

Third, in main(), you call getInput() like this:

getInput(list, dim);

So, your code should look like this:

#include<iostream>
#include<iomanip>

void getInput(std::vector<int>& list);

int main()
{
    int dim{};

    std::cout << "enter number: " << '\n';
    std::cin >> dim;
    
    std::vector <int> list(dim)

    getInput(list);    
}


void getInput(std::vector<int>& list);
{       
    for(int i = 0; i < list.size(); i  )
    {
        std::cout << "loc["<<i<<"] ";
        std::cin >> list[i];
    }
}

CodePudding user response:

You are using incorrect syntax to call the function getInput.

Moreover inside your main() function there is no object named list or dim. So you must first create an object named list and dim and then pass those as arguments to the function getInput as shown in the example given below.

If you want to take the size of the array as input then std::vector would be a better choice since the size of a built in array must be a compile time constant in c .

With std::vector you can do what you want as shown:

#include<iostream>
#include<iomanip>
#include <vector>
using namespace std;

//no need to pass the second argument since we can use std::vector::size
void getInput(std::vector<int>& list);//getInput is a function that takes a listtor by reference as argument


int main()
{

    int dim = 0;
    cout<<"enter number: "<<endl;
    std::cin >> dim;
    std::vector<int> list(dim);//create a vector of size dim 
    getInput(list);//call function

    
}


void getInput(std::vector<int> &list)
{       
    for(int i = 0; i < list.size(); i  )//note i have used list.size()
    {
        cout<<"loc["<<i<<"] ";
        cin>>list[i];
    }
}

  •  Tags:  
  • c
  • Related