简体   繁体   中英

allocate a new memory for matrix of objects

I have the class Cars and the object (pointer to pointers of digits):

Cars** arr;

I want to allocate a new memory, how can I do it?

something like:

arr = new Cars*[1]; // make one row
arr[0] = new Cars[10]; // make 10 cols

for (int i = 0; i < 10; ++i) {
    arr[0][i] = d; // d is a parameter of: Digits d;
}

I set rows = 1 because I think there is always 1 row.

please help me cause I think I miss something..

arr = new Cars*[1]; // make one row
arr[0] = new Cars[10]; // make 10 cols
for (int i = 0; i < 10; ++i) {
   arr[0][i] = d; // d must be an object of Cars
}

since arr stores elements of Cars type, d must be an object of Cars or can be converted to/viewed as object of Cars .

You'd better to use vector of vectors instead, which is easier to use and you don't need to bother with the memory management issue with dynamic arrays.

Set it to std::vector instead

std::vector<std::vector<Cars>> arr;
arr.resize(1); // make one row
arr[0].resize(10); // make 10 cols

for (int i = 0; i < 10; ++i) {
    arr[0][i] = d; // d is a parameter of: Digits d;
}

Note: d must be a Car.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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