繁体   English   中英

动态分配数组(向量实现的动态大小)

[英]Dynamic allocating an array (dynamic size of the vector implementation)

在obj-c中,我们可以创建矢量对象,如下所示:

SomeClass* example[100];

要么

int count[7000];

但是如果我们只在初始化时才知道向量的大小呢? (也许我们需要例子[756]或计数[15])

首先,那些不是矢量对象,它们是编译时数组。 编译时阵列的一个特性是自动内存管理; 也就是说,您不必担心这些数组的分配和释放。

如果要创建一个在运行时之前不知道其大小的数组,则需要使用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;

如果您忘记使用相应的delete 1取消分配new创建的内容,则会产生内存泄漏

你可能最好使用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确保在使用new创建的指针上使用delete ,并使用new[x]在指针上delete[] new[x] 不要混合搭配 同样,如果你使用std::vector ,你不必担心这个。

为什么不使用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
}

然后你做的事情如下:

SomeClass **example = calloc(numClasses, sizeof(SomeClass *));

要么:

int *count = malloc(num_of_counts * sizeof(int));

请注意,您应该:

#include <stdlib.h>

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一无所知,但你的问题可能只有一个或另一个。

暂无
暂无

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

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