013 Passing a Pointer to a Function

Instructions

Problem Statement:

Pointers are a fundamental aspect of C++. They allow for flexible and efficient programming by giving direct access to memory. You are tasked with writing a function that uses a pointer to multiply an integer value.

Write a function:

void multiply_with_pointer(int* ptr, int multiplier);


Input:

Output:

The function should multiply the integer at the memory address that ptr points to by multiplier.


Function signature:

void multiply_with_pointer(int* ptr, int multiplier);


Constraints:

Test(s)

Test 1

#include "gtest/gtest.h"
#include "helpers/iohelper.h"

void multiply_with_pointer(int* ptr, int multiplier);

namespace {

class Evaluate : public ::testing::Test {

protected:
    Evaluate() {
        // You can do set-up work for each test here.
    }

    virtual ~Evaluate() {
        // You can do clean-up work that doesn't throw exceptions here.
    }

    // Objects declared here can be used by all tests in the test case for Foo.
};

TEST_F(Evaluate, Test1) {
  int a = 5;
  multiply_with_pointer(&a, 2);
  EXPECT_EQ(a, 10);

}

TEST_F(Evaluate, Test2) {
    int a = 20;
  multiply_with_pointer(&a, 5);
  EXPECT_EQ(a, 100);

}

TEST_F(Evaluate, Test3) {
    int a = 50;
  multiply_with_pointer(&a, 1);
  EXPECT_EQ(a, 50);

}
TEST_F(Evaluate, Test4) {
    int a = 100;
  multiply_with_pointer(&a, 100);
  EXPECT_EQ(a, 10000);

}


}  // namespace

Solution(s)

Solution 1

void multiply_with_pointer(int* ptr, int multiplier) {
    *ptr *= multiplier;
}

Solution 2

void multiply_with_pointer(int* ptr, int multiplier) {
    *ptr *= multiplier;
}