Dynamic array....probable memory allocation problem..need advise!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Baka otaku
    New Member
    • Feb 2007
    • 4

    Dynamic array....probable memory allocation problem..need advise!

    The program I need to write must accept code no, name and total bill amount for "n" number of customers and then print all the things along with the grand total. I worked out the program and while building it shows no errors. while debugging, it takes the first set of values but after that it says - The instruction at "0x00402161 " referenced memory at "0xcccccccc ". The memory could not be "written". Is there something wrong with the program or memory...please help.

    The code is :

    Code:
    #include<iostream>
    using namespace std;
    
    class customer
    { private:
    int ncust;
    int *codeno;
    char **name;
    int *tbill;
    
    public: 
    void cust_accept(void);
    void cust_print(void);
    };
    
    void customer::cust_accept(void)
    { cout << "Enter the total number of customers " << endl;
    cin >> ncust;
    codeno=(int*)new int[ncust]; 
    name=(char**)new char*[ncust];
    for (int i=0; i<ncust; i++)
    { name[i]=(char*)new char[20];
    }
    for (int j=0; j<ncust; j++)
    { cout << "Enter the customer code no " << endl;
    cin >> codeno[j];
    cout << "Enter customer name " << endl;
    cin >> name[j]; // insert name of customer
    cout << "Enter the total bill amount " << endl;
    cin >> tbill[j];
    }
    }
    
    void customer::cust_print(void)
    { for(int i=0;  i<ncust; i++)
    { cout << "Customer" << endl; 
    cout << "Code no   Name   Total Bill amount " << endl;
    cout << codeno[i] ;
    cout << name[i] ;
    cout << tbill[i];
    }
    int gtotal;
    for (int j=0; j<ncust; j++)
    {gtotal+=tbill[j];
    cout << endl;
    cout << "Grand total" << gtotal;
    }
    }
    
    
    int main ()
    { customer srec;
    srec.cust_accept();
    srec.cust_print();
    return 0;
    }
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    the memory you allocate for name is the number of customers
    Code:
    name=(char**)new char*[ncust];
    so if ncust is 3 each name is a maximum of 2 characters long
    perhaps it should be
    Code:
    name=(char**)new char*[20];
    and the name can be up to 20 characters long.

    would it not be better for class customer to hold data on one customer and then have a vector of customers?
    Code:
        vector<customer> v;

    Comment

    Working...