I want to create a two-dimensional dynamic array in which the element will be an array of char characters (also dynamic) ... how to implement it?

void making_an_array(int**&p_arr, int const rows, int const cols) { p_arr = new int*[rows]; for (int i = 0; i < rows; i++) p_arr[i] = new int[cols]; } 

here the function creates a two-dimensional array int and in my element will be char ... how to be?

 void create_a_string_element() { int symbol_number{}; int string_size = rand() % 5 + 5; char *string_element = new char[string_size + 1]; for (int j = 0; j <= string_size; j++) { symbol_number = rand() % 32 + 192; if (j == string_size) string_element[j] = '\0'; else string_element[j] = symbol_number; } delete[]string_element; } 

and here I create my element. Engaged in self-education

  • You need to initially create a pointer to a pointer. That is char ** string_element. And then the pointer to the pointer should be assigned a pointer to the Charovsky dynamic array - Vladimir Afanasyev
  • Int first, second; fd = new char**[first]; for(int i = 0; i<first; i++) fd[i] = new char*[second]; I can not guarantee the exact syntax, wrote in haste on the phone - Vladimir Afanasyev
  • first, second what's this? rows, cols as in my function ... this is the same as mine ... it's just a two-dimensional array ... the size of the char [???] is unknown ... it is defined in the function itself ... - alexey shabaldas
  • And what's the difference, where to determine: in the function or not? You can pass as a parameter to a function and create it in a function. You can generate a size arbitrarily. Essentially it does not change - Vladimir Afanasyev
  • and now in the second loop, assign fd [i] = my char element from my function? I understand correctly? - Alexey Shabaldas

1 answer 1

 int first, second; fd = new char**[first]; for(int i = 0; i<first; i++) fd[i] = new char*[second]; for(int i = 0; i<first; i++) for(int j = 0; j<second; j++) fd[i, j] = ... 

In a hurry, it looks something like this

  • int first, second; fd = new char ** [first]; for (int i = 0; i <first; i ++) fd [i] = new char * [second]; for (int j = 0; j <second; j ++) fd [i, j] = ... - Alexey Shabaldas
  • What is the question? .. - Vladimir Afanasyev
  • Everything worked out! Thank you! - Alexey Shabaldas
  • void making_an_array (char *** & arr, int const rows, int const cols) {char * string_element; arr = new char ** [rows]; for (int i = 0; i <rows; i ++) {arr [i] = new char * [cols]; for (int j = 0; j <cols; j ++) {create_a_string_element (string_element); arr [i] [j] = string_element; }}} - Alexey Shabaldas
  • Don't forget to free the memory from the array at the end - Vladimir Afanasyev