在obj-c中,我们可以按如下方式创建矢量对象:
SomeClass* example[100];
或
int count[7000];
但是,如果我们只在初始化时才知道向量的大小呢? (也许我们需要例子[756]或计数[15])
答案 0 :(得分:3)
首先,那些不是矢量对象,它们是编译时数组。编译时阵列的一个特性是自动内存管理;也就是说,您不必担心这些数组的分配和释放。
如果要创建一个在运行时之前不知道其大小的数组,则需要使用new[]
和delete[]
:
int size = somenumber;
int* arr = new int[size];
// use arr
arr[0] = 4;
// print the first value of arr which is 4
cout << arr[0];
问题在于,在完成此数组后,您必须取消分配它:
delete[] arr;
如果您忘记要取消分配由new
创建的具有相应delete
1 的内容,您将创建memory leak
您可能最好使用std::vector
,因为它会自动为您管理内存:
// include the header
#include <vector>
using namespace std; // so we don't have std:: everywhere
vector<int> vec; // create a vector for ints
vec.push_back(4); // add some data
vec.push_back(5);
vec.push_back(6);
// vec now holds 4, 5, and 6
cout << vec[0]; // print the first element of vec which is 4
// we can add as many elements to vec as we want without having to use any
// deallocation functions on it like delete[] or anything
// when vec goes out of scope, it will clean up after itself and you won't have any leaks
1 请确保对使用delete
和new
创建的指针使用delete[]
指向new[x]
指针。 不要混用和匹配。同样,如果您使用std::vector
,则无需担心此问题。
答案 1 :(得分:2)
为什么不使用std :: vector
//file.mm
#include <vector>
-(void)function
{
std::vector<int> count;
std::vector<SomeClass*> example;
count.push_back(10); // add 10 to the array;
count.resize(20); // make count hold 20 objects
count[10] = 5; //set object at index of 10 to the value of 5
}
答案 2 :(得分:1)
然后你做了类似的事情:
SomeClass **example = calloc(numClasses, sizeof(SomeClass *));
或:
int *count = malloc(num_of_counts * sizeof(int));
请注意:
#include <stdlib.h>
答案 3 :(得分:1)
C ++不能生成可变大小的全局/本地数组,只能生成堆上的动态数组。
int main() {
int variable = 100;
SomeClass* example = new SomeClass[variable];
//do stuff
delete [] example; //DO NOT FORGET THIS. Better yet, use a std::vector
return 0;
}
我对Objective-C一无所知,但你的问题可能只有一个。