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 5×5):

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));

Source: Windows Questions C++

LEAVE A COMMENT