A few things to note:
- You don't have to cast the return value of malloc.
- You don't have to cast the pointer to void* to use free.
- Besides using free for each inner dynamic array, you should also use it for the outer dynamic array.
- sizeof(char) == 1 is always true, so either omit it, or use the idiom:
Code:
temp = malloc(sizeof(*temp) * row);
- If each of the inner arrays will always be of the same size, then this method is unnecessarily expensive.
For the last point, an alternative is:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
const char str[] = "Copying Test";
int num_rows = 5;
int num_cols = sizeof(str);
/* Assume that malloc does not return a null pointer */
char *data = malloc(sizeof(*data) * num_rows * num_cols);
char **temp = malloc(sizeof(*temp) * num_rows);
int i;
for (i = 0; i < num_rows; ++i)
{
temp[i] = &data[i * num_cols];
memcpy(temp[i], str, num_cols);
}
for (i = 0; i < num_rows; ++i)
{
printf("%s\n", temp[i]);
}
free(temp);
free(data);
return 0;
}
Incidentally, considering that you use cout: is this C or C++?