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:
new
? Shouldn't we use sizeof(S)
somewhere?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));
sizeof(S)
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