exercise on pointers

Asked

Viewed 77 times

0

Implements the function void power_ref(int* x, int y) which calculates the power of x leading to y. The result must be placed at the address indicated in the first parameter, changing its initial value.

I have something like this:

#include <stdio.h> 

void power_ref(int* x,  int y){

    int result = (int) *x ^ y;
    *x  = result;
    printf("result: %d", result);
}
  • What is your difficulty in exercise?

  • Because the x is a pointer and the function is void? It would not be simpler and more natural to return the calculated value?

  • is as they ask in the ex , the difficulty is with the Pointer because I do not know well how to use it

  • I have put what I have asked in the question above

  • You know how to do a function int power(int x, int y)? If yes, post it that based on it it is easy to do the power_ref.

  • The ^ in C does not exponenciate. The ^ in C is the XOR (or-exclusive). That’s not what you’ll need to use. You’ll need a for.

  • so that one is?

  • To make successive multiplications.

Show 3 more comments

1 answer

0

Solution #1:

void power_ref( int * x, int y )
{
    int i = 0;
    int n = 1;

    for ( i = 0; i < y; i++ )
        n *= (*x);

    *x = n;
}

Solution #2:

#include <math.h>

void power_ref( int * x, int y )
{
    *x = pow( *x, y );
}

Solution #3:

void power_ref( int * x, int y )
{
    int n = 1;
    int b = *x;

    while(y)
    {
        if(y & 1)
            n *= b;
        y >>= 1;
        b *= b;
    }

    *x = n;
}

Testing:

#include <stdio.h>

int main( void )
{
    int n = 2;

    power_ref( &n, 16 );

    printf( "%d\n",  n );

    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.