c++ - Returning and using a pointer to a multidimensional array of another class -
i'm trying access 'room' array via functions in room class itself, i.e:
class ship{ room * rooms[3][4]; public: room ** getrooms(){ return *rooms; } } class room{ //variables... ship * ship_ptr; public: getshipptr(); //assume returns pointer class ship void function_x(){ this->getshipptr()->getrooms()->rooms[x][y]->dothat(); } } i'm doing wrong pointer-wise i'm not sure, correct code can access room array out of ship class? note: assume rooms initiated
i'm doing wrong pointer-wise i'm not sure
you making false assumption 2d array can decay pointer pointer 1d array can decay pointer.
int arr1[10]; int* ptr1 = arr1; // ok. 1d array decays pointer. int arr2[10][20]; int** ptr2 = arr2; // not ok. 2d array not decay pointer pointer. int (*ptr2)[20] = arr2; // ok. ptr2 pointer "an array of 20" objects. my suggestion:
simplify code , change interface to:
room* getroom(size_t i, size_t j){ // add checks make sure , j within bounds. return rooms[i][j]; }
Comments
Post a Comment