You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++动态分配对象数组时出现段错误问题求助

段错误原因分析与代码修正

核心问题

  1. 变量重名+非法数组定义:全局指针ptr被循环内的同名局部product数组覆盖,且product ptr[i];是非法的变长数组(C++标准不允许数组大小为运行时变量),当i=0时创建长度为0的数组直接触发内存错误。
  2. 对象未持久化存储:循环内创建的product对象是局部变量,循环结束后立即销毁,完全无法保存数据。
  3. 逻辑混淆:原本想用ptr关联产品数量和产品对象,结果变量复用导致指针指向混乱,后续访问越界引发段错误。

修正后的代码

#include<iostream>
#include<string>
using namespace std;

class Product {
    string name;
public:
    void add() {
        cout << "输入产品名称:" << endl;
        cin >> name;
    }
    // 新增打印方法,用于展示产品信息
    void show() const {
        cout << "产品名称:" << name << endl;
    }
};

int main() {
    int productCount;
    cout << "客户购买了多少种产品?" << endl;
    cin >> productCount;

    // 动态分配Product数组,存储所有产品对象
    Product* products = new Product[productCount];
    // 单独分配int数组存储每种产品的购买数量
    int* buyCounts = new int[productCount];

    for (int i = 0; i < productCount; ++i) {
        cout << "请输入第" << i+1 << "种产品的购买数量:" << endl;
        cin >> buyCounts[i];
        cout << "请输入第" << i+1 << "种产品的名称:" << endl;
        products[i].add();
        cout << "-------------------------" << endl;
    }

    // 展示所有产品信息
    cout << "\n购买的产品列表:" << endl;
    for (int i = 0; i < productCount; ++i) {
        cout << "第" << i+1 << "种:" << endl;
        cout << "购买数量:" << buyCounts[i] << endl;
        products[i].show();
        cout << "-------------------------" << endl;
    }

    // 释放动态分配的内存,避免内存泄漏
    delete[] products;
    delete[] buyCounts;

    return 0;
}

修正说明

  • 拆分了产品对象数组和购买数量数组,彻底避免变量重名与逻辑混淆。
  • 使用new Product[productCount]动态分配产品对象数组,确保数据能在循环外持久化存储。
  • 新增show方法用于展示产品信息,满足“存储数据并可查看”的需求。
  • 手动释放动态分配的内存,避免内存泄漏问题。

内容的提问来源于stack exchange,提问作者vivek Rai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 13:50:41