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 = newchar[5];
for(int i=0; i<=5; i++) ch[i] = newchar[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 = newchar*[5]; // new char* not new char
for(int i=0; i<5; i++) // < 5, not <= 5
ch[i] = newchar[x[i]];
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++.