Dynamic allocating an array (dynamic size of the vector implementation)
In the obj-c, we can create vector objects as follows:
SomeClass* example[100];
or
int count[7000];
But what if we know the size of the vect开发者_StackOverflow中文版or only at the time init the class? (Maybe we need example[756] or count[15])
First of all, those aren't vector objects, they're compile-time arrays. One of the features of compile time arrays is automatic memory management; that is, you don't have to worry about allocation and deallocation of these arrays.
If you want to create an array whose size you don't know until runtime, you'll need to use new[]
and 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];
The catch is that after you're done with this array, you have to deallocate it:
delete[] arr;
If you forget to deallocate something created by new
with a corresponding delete
1, you'll create a memory leak.
You are probably better off using std::vector
though because it manages memory for you automatically:
// 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 Make sure you use delete
on pointers that you created with new
and delete[]
on pointers you make with new[x]
. Do not mix and match them. Again, if you use std::vector
, you don't have to worry about this.
Why not just use an 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
}
Then you do something like:
SomeClass **example = calloc(numClasses, sizeof(SomeClass *));
or:
int *count = malloc(num_of_counts * sizeof(int));
Note that you should:
#include <stdlib.h>
C++ cannot make global/local arrays of a variable size, only dynamic arrays on the heap.
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;
}
I don't know anything about objective-C, but your question is probably only one or the other.
精彩评论