C memory allocation to c++

This is a discussion on C memory allocation to c++ within the C++ Programming forums, part of the General Programming Boards category; Hi, I would like to convert my c style memory allocation (calloc) to c++ style (new and delete). The way ...

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    38

    C memory allocation to c++

    Hi,

    I would like to convert my c style memory allocation (calloc) to c++ style (new and delete). The way I am doing it at the moment in c is as follows:

    Code:
    char** seq_array;
    seq_array = (char **)calloc( (nseqs) * sizeof (char *), sizeof(char) );
    
    for(int i=0; i < nseqs; i++)
    seq_array[i] = (char *)calloc((length) * sizeof (char), sizeof(char));

    This is to generate an array of size nseqs*length. I would like to change this to the c++ way of allocating memory. Would it be something like the following:

    Code:
    seq_array = char**[nseqs][length];

    And what about freeing up the memory?

    Thanks for your help
    Mark

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,202
    Code:
    char **seq_array;
    seq_array = new (char *)[nseqs];
    for (int i = 0; i < nseqs; ++i)
      seq_array = new char[length];
    The only differences is that, unlike calloc(), operator new does not guarantee initialisation to zero for basic types. To achieve that, modify the above to;
    Code:
    char **seq_array;
    seq_array = new (char *)[nseqs];
    for (int i = 0; i < nseqs; ++i)
    {
        seq_array = new char[length];
        for (int j = 0; j < length; ++j)
           seq_array[i][j] = 0;
    }
    Incidentally, the original versions with calloc() contains a minor error. It should be
    Code:
    char** seq_array;
    seq_array = (char **)calloc( (nseqs) * sizeof (char *), sizeof(char *) );
    
    for(int i=0; i < nseqs; i++)
    seq_array[i] = (char *)calloc((length) * sizeof (char), sizeof(char));
    In this example, it doesn't matter as the subsequent loop overwrites each element of seq_array, but remove that loop ......

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    38

    Thanks

    Thanks very much for you reply

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory allocation question
    By dakarn in forum C Programming
    Replies: 11
    Last Post: 12-01-2008, 10:41 PM
  2. Relate memory allocation in struct->variable
    By Niara in forum C Programming
    Replies: 4
    Last Post: 03-23-2007, 03:06 PM
  3. Dynamic memory allocation.
    By HAssan in forum C Programming
    Replies: 3
    Last Post: 09-07-2006, 05:04 PM
  4. Dynamic memory allocation...
    By dicorr in forum C Programming
    Replies: 1
    Last Post: 06-24-2006, 03:59 AM
  5. Understanding Memory Allocation
    By Ragsdale85 in forum C Programming
    Replies: 7
    Last Post: 10-31-2005, 07:36 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21