0

Please keep in mind that I can't use classes or vectors, only arrays.

Anyway I have something like this so far:

int** arrays = new int*[10]; 
arrays[0] = new int[99]; 
arrays[1] = new int[47]; 

I'm not entirely sure but I think it would be possible to put values within the array that is getting pointed to the same way you would for a 2D array.

So would something like this work?

arrays[1][30] = 5;

Also if I wanted to delete one of the arrays (not the array pointer) would it be possible to do:

delete[] arrays;
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user3247278
  • 179
  • 2
  • 3
  • 13

2 Answers2

1

In C++ every call to new should have matching call to delete. So when you initialize array

int **arrays = new int*[10];
arrays[0] = new int[99]; 
arrays[1] = new int[47];

you have to delete it with

delete [] arrays[0];
delete [] arrays[1];
delete [] arrays;

In general case read this answer and whole thread.

A call to

arrays[1][30] = 5;

is fine because memory has already been allocated.

Community
  • 1
  • 1
4pie0
  • 29,204
  • 9
  • 82
  • 118
0

In order: Yes it would (with risks), and no it won't.

For the first, you need to remember (as always) how many elements are in the array so you don't run off the end. One each way might be to use a structure:

typedef struct {
    int len;
    int* contents;
} FiniteArray;

Then make int** arrays actually be an array of FiniteArray structures, itself a FiniteArray*.

If you're 100% set on using arrays, you still can, just keep lengths around at all times. Don't forget, of course: you need the number of elements in arrays too!

For the second part with delete[], that will delete your array of arrays but will leave the rest of the memory allocated!

You are correct in that, when you use new for an array, you use delete[]. Otherwise, for objects, use delete, etc etc. See this question. Yes, I know it's a duplicate, but I thought it explains this better than what it's marked duplicate of.

Anyway, you will need to first deallocate the individual arrays if you want to delete arrays. In your case,

delete[] arrays[0];
delete[] arrays[1];
delete[] arrays;
arrays = NULL; // always a good idea!

Just to delete one array, say, the first one,

delete[] arrays[0];
arrays[0] = NULL; // always a good idea!
Community
  • 1
  • 1
Gutblender
  • 1,340
  • 1
  • 12
  • 25