Creating a multi-dimensional dynamic array

Hi, I'm trying to create a multi-dimensional dynamic array, with one dimension as a fixed value.
I've tried something like this:

1
2
3
4
5
int fixedVal = 15;
int dynamicVal;
cin >> dynamicVal;
int *x;
x = new int[15][dynamicVal]; // or vice versa 


But it doesn't work. Is there anyway to resolve this ?
You cannot create a multi-dimensional pointer with what I know cause I've never seen one before
You mean like this?
1
2
3
4
5
const int fixedVal = 15;
int dynamicVal;
cin >> dynamicVal;
int (*x)[fixedVal];
x = new int[dynamicVal][fixedVal];
You cannot create a multi-dimensional pointer

It is possible, but it's easier to see with c-strings than ints

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <cstring>

int main(void)
{  
  /* Create the seed  (note the last word's length is zero) */
  const char *line[] = {"Hello", "world. ", "Nice", "to", "meet", "you.", ""};
  
  /* A char pointer pointer */
  char **words = NULL;
  
  /* Figure out how many words there are */
  int amountOfWords = 0;
  for (int pos = 0; strlen(line[pos]) > 0; pos++)
    amountOfWords++;
  
  /* Make words be an array of char pointers, the size of the amount of words */
  words = new char*[amountOfWords];
  
  
  /* The pointers in the words array can be used like any other 
   * You simply have an array of them */
  for (int i = 0; i < amountOfWords; i++)
  {
    words[i] = new char[strlen(line[i]) + 1];
    strcpy(words[i], line[i]);
  }
  
  /* Print 'em out */
  for (int i = 0; i < amountOfWords; i++)
    std::cout << words[i] << " ";
  std::cout << '\n';
  
  
  /* Clean up */
  for (int i = 0; i < amountOfWords; i++)
    delete [] words[i];
  
  delete [] words;
  return 0;
}


now you've seen it :)
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
int fixedValue = 15;
int dynamicValue;

cin >> dynamicValue;
int **matrix;

matrix = new int*[fixedValue];
for(int i = 0; i < fixedValue; i++)
    matrix[i] = new int[dynamicValue];

for(int r = 0; r < fixedValue; r++)
    for(int c = 0; c < dynamicValue; c++)
        m[r][c] = 0; 


Makes a pointer array of pointers making it 2D, also initializes all values to 0.

line 7 creates the first 'fixed' array of size 15.

for loop on line 8 creates an array of 'dynamic size' in each of the first's array slots.

loop through row and column just like any other 2D array to initialize.

I know this works because I did it for my matrix header for a homework assignment.

Hope it helps,
Anthony
Last edited on
@Lowest One

Thanks for broadening my knowledge!!!
Topic archived. No new replies allowed.