Array of differently sized arrays

So, a thought occurred to me to a problem I had never encountered before...Can you dynamically allocate a multidimenional array with different sizes in the sub arrays...


for instance assume the following code:

1
2
3
4
5
6
7
8
9
 int x[5];
srand();
for(int i = 0; i<=5; i++) x = rand() % 5;

char **ch;

ch = new char[5];
for(int i=0; i<=5; i++) ch[i] = new char[x[i]];
 


is this legal? or will i get a segfault or something..I've never really thought about this.
Can you dynamically allocate a multidimenional array with different sizes in the sub arrays...


Yes. This is one of the very few legitimate reasons to use a nested new MD array over a linear 1D array.

But your code has several flaws. Here are corrections:

1
2
3
4
5
6
7
8
9
10
11
12
13
 int x[5];
srand();

for(int i = 0; i<5; i++)  // < 5, not <= 5.
  x[i] = rand() % 5;  // this is also bad because you don't want x to be zero.  allocating 0 elements will fail
                 // and also x[i] not x

char **ch;

ch = new char*[5];  // new char*  not new char
for(int i=0; i<5; i++)  // < 5, not <= 5
  ch[i] = new char[x[i]];
 
lol, yea I kinda just pissed it out for the sake of asking the question, I figured there would be some flaws, thank you though :D

They are called jagged arrays.
closed account (1yR4jE8b)
Jagged Arrays are usefull for implementing Undirected Graphs if you want to save memory, because the values of the graph[i][j] for an undirected graph should be the same for graph[j][i]. Hence you can use a jagged array and ignore the 'bottom half' of the graph.

I had to prove to my professor that this was actually possible using Java. Although it is quite trivial for C/C++.
Topic archived. No new replies allowed.