MST

星途 面试题库

面试题:C++指针函数返回值的常规处理

请编写一个C++指针函数,该函数接收两个整数参数,返回它们乘积的指针。在主函数中调用该指针函数,并正确处理返回的指针,包括内存释放,避免内存泄漏。
39.8万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>

// 指针函数,返回两个整数乘积的指针
int* multiply(int a, int b) {
    int* result = new int(a * b);
    return result;
}

int main() {
    int num1 = 5;
    int num2 = 3;

    int* productPtr = multiply(num1, num2);
    if (productPtr) {
        std::cout << "The product of " << num1 << " and " << num2 << " is: " << *productPtr << std::endl;
        delete productPtr; // 释放内存,避免内存泄漏
        productPtr = nullptr; // 将指针置为nullptr,防止悬空指针
    }

    return 0;
}