简体   繁体   English

如何将值放入动态数组数组中,并在C ++中删除它们

[英]How can I put values inside dynamic arrays of arrays and also delete them in c++

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. 我不确定,但我认为可以将值放置在指向2D数组的数组中。

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;

In C++ every call to new should have matching call to delete. 在C ++中,每个对new的调用都应具有匹配的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. 很好,因为已经分配了内存。

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* . 然后,使int** arrays实际上是FiniteArray结构的数组,其本身就是FiniteArray*

If you're 100% set on using arrays, you still can, just keep lengths around at all times. 如果您100%准备使用数组,则仍然可以,只要始终保持长度不变即可。 Don't forget, of course: you need the number of elements in arrays too! 当然,不要忘记:您也需要arrays的元素数量!

For the second part with delete[] , that will delete your array of arrays but will leave the rest of the memory allocated! 对于带有delete[]的第二部分,这将删除您的数组数组, 但剩下的内存将被分配!

You are correct in that, when you use new for an array, you use delete[] . 正确的是,当对数组使用new时,请使用delete[] Otherwise, for objects, use delete , etc etc. See this question . 否则,对于对象,请使用delete等。请参见此问题 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 . 无论如何,如果要删除arrays ,则需要先释放各个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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM