Search code examples
c++arraysmallocdynamic-memory-allocationnew-operator

User defined type used in dynamic allocated 2d array


Let's assume that we have a simple struct

struct S {
     int a;
     int b;
     int c;
}

Now we want to create an array of pointers (2d array 5x5):

S** arr = new S*[5];
for (int i = 0; i < 5; ++i)
    arr[i] = new S[5];

My questions are:

  1. Is it a correct way to dynamically allocate a memory for this array using new? Shouldn't we use sizeof(S) somewhere?
  2. How would the code look like if using malloc instead of new? Is the code below correct?
S** arr = (S**)malloc(5 * sizeof(S));
for (int i = 0; i < 5; ++i)
    arr[i] = (S*)malloc(5 * sizeof(S));

Solution

    1. Yes, this is correct way. No, there is no need to use sizeof(S)
    2. Your code isn't correct. Generally you shouldn't use malloc if struct S have non-trivially-copiable members, but if S satisfy that, your code should look like this:
    S** arr = (S**)malloc(5 * sizeof(S*));
    for (int i = 0; i < 5; ++i)
        arr[i] = (S*)malloc(5 * sizeof(S));
    

    But using malloc in C++ is considered as bad practice. And I would try to rewrite it using std::vector if you can. And of course don't forget to clear memory with delete/free in case of using new/malloc