Home > Net >  Pointers Pass by Reference Powered
Pointers Pass by Reference Powered

Time:02-21

I need to create a void function that gives the powered result of the user input. I keep getting an error on line 15 that says

expected primary expression before int

Does anyone know why this is happening?

#include <iostream>
using namespace std;

void powered(int* x, int y);

int main()
{
    int *numPtr;
    int power;

    cout << "Enter an integer and its power: ";
    cin >> *numPtr;
    cin >> power;
    powered(int *numPtr, &power);
    cout << "Result is " << *numPtr << endl;

    return 0;
}

void powered(int* x, int y)
{
    for(int i = 1; i <= y; i  ){
        *x = *x * y;
    }
}

This is the sample output:

Enter an integer and its power: 3 4

Result is 81

CodePudding user response:

There's a bug in your code

int *numPtr;

This creates an uninitialized pointer object. It's not pointing to an actual int. So using it is undefined behavior. Don't use a pointer here.

Because we're using C , and your question literally says "reference" in the title, you should use "pass by reference" for this. I.e.

void powered(int& x, int y)
{
    for(int i = 1; i <= y;   i){
        x *= y;
    }
}

Then you can just pass

int main()
{
    int num;
    int power;

    std::cout << "Enter an integer and its power: ";
    std::cin >> num;
    std::cin >> power;
    powered(num, power);
    std::cout << "Result is " << num << '\n';

CodePudding user response:

This is because your powered(int* x, int y) is expecting a pointer in first argument, and int value in second argument. Furthermore, your algorithm for calculating power has logic error. I will leave it to you. Your function call should be:

#include <iostream>
using namespace std;

void powered(int* x, int y);

int main()
{
    int num;
    int power;

    cout << "Enter an integer and its power: ";
    cin >> num;
    cin >> power;
    powered(&num, power);
    cout << "Result is " << num << endl;

    return 0;
}

Note that & operator extracts the pointer of num. Dereference operator * is unnecessary to your main function.

  •  Tags:  
  • c
  • Related