c++ - Attempting to create a dynamic array -


i have following piece of code, half on entire code:

// declare map elements using enumeration enum entity_labels {     empty = 0,     wall }; typedef entity_labels   entity;  // define array of ascii codes use visualising map const int token[2] = {     32,     // empty     178     // wall };  // create type aliases console , map array buffers  using gui_buffer = char_info[map_height][map_width]; using map_buffer = entity[map_height][map_width];  //declare application subroutines void initconsole(unsigned int, unsigned int); void clearconsole(handle hstdout); word getkey(); void drawmap(map_buffer & rmap);   /**************************************************************************   * initialise standard output console   */ handle  hstdout = getstdhandle(std_output_handle); if (hstdout != invalid_handle_value) {     clearconsole(hstdout);      // set window title     setconsoletitle(text("tile map demo"));      // set window size     small_rect srwindowrect;     srwindowrect.left = 0;     srwindowrect.top = 0;     srwindowrect.bottom = srwindowrect.top + map_height;     srwindowrect.right = srwindowrect.left + map_width;      setconsolewindowinfo(hstdout, true, &srwindowrect);      // set screen buffer size     coord cwindowsize = { map_width, map_height };     setconsolescreenbuffersize(hstdout, cwindowsize); } /*************************************************************************/   /************************************************************************* * initialise tile map appropriate entity values */  map_buffer tilemap;  (unsigned int row = 0; row < map_height; row++) {     (unsigned int col = 0; col < map_width; col++)     {         tilemap [row][col] = wall;     } } 

essentially entire code used create tile map , output screen i'm attempting make tilemap dynamic array in runtime. have tried creating 1 down tilemap being created. i've tried creating 1 after "entity_lables" given typedef "entity". i've tried creating 1 after "map_buffer" , "gui_buffer" become aliases. still i'm @ loss, have no idea on how implement dynamic array tilemap, , don't know best spot put it.

any appreciated.

the syntax using defining array constant sized c array. in general should shy away c arrays unless size of data determined @ compile time(and never needs change) , array never leaves scope(because c array not retain information on own size.)

in place of constant or dynamically sized c arrays suggest use vector container. vector dynamically sized container fills back, last element have added to

std::vector<std::vector<entity>> 

to add vector container project add line

#include <vector> 

to fill container loop like:

map_buffer tilemap;  (unsigned int row = 0; row < map_height; row++) {     std::vector<entity> column; // column of tile map     (unsigned int col = 0; col < map_width; col++)     {         column.push_back(wall); // add 1 element column     }     tilemap.push_back(column); // add column tile map } 

or initialize vector size want @ beginning , use current loop assign tile values:

using tile_map = vector<vector<entity>>; // map_width x map_height multidimensional vector tile_map tilemap(map_width, vector<entity>(map_height));   (unsigned int row = 0; row < map_height; row++) {     (unsigned int col = 0; col < map_width; col++)     {         tilemap [row][col] = wall;     } } 

calling element of vector after has been filled has same syntax array.

tilemap[2][4] 

you can check length of vector:

int rows = tilemap.size(); if( rows > 0 )    int columnsinrow0 = tilemap[0].size() 

while @ should other containers maps , sets since make life easier.

edit:

since want know how make dynamic array not using vector give answer: std::vector c++ defined dynamically sized array. c arrays not change size after defined, vector will.

however think asking ability define runtime constant sized arrays. explain , why should not use them.

when define c array getting warning saying expression needs constant.

a c array pointer stack. , implementation of compiletime c array needs constant size @ compile time.

int compiletimearray[] = { 1, 2, 3 }; // turns out c arrays pointers int* ptr = compiletimearray; // prints 2 std::cout << compiletimearray[1]; // prints 2 std::cout << ptr[1]; // prints 2 std::cout << *(compiletimearray + 1); // prints 2 std::cout << *(ptr + 1); //move pointer 1 element , de-reference 

pointers whiteboard telephone number written on it. same kind of issues occur telephone numbers; number on whiteboard has been erased, number on whiteboard has changed, recipient not exist, recipient changed number, service provider running out of available numbers give new users... keep in mind.

to create runtime constant sized array need allocate array on heap , assign pointer.

int size = 4; int* runtimearray = new int[size];           // work delete[] runtimearray;                       // de-allocate size = 8;                                    // change size runtimearray = new int[size];                // allocate new array 

the main difference between stack , heap stack de-allocate memory used variable when program exits scope variable declared in, on other hand declared on heap still remain in memory , has explicitly de-allocated or memory leak.

 // must call when never going use data @ memory address again  // release memory heap  delete[] runtimearray; // akin releasing phone number used else 

if not release memory heap run out.

 // try running  void crashingfunction() {    while(true)    {        // every time new[] called ptr assigned new address, memory @ old address not freed        // 90001 ints worth of space(generally 32 or 64 bytes each int) reserved on heap        int* ptr = new int[90001]; // new[] crashes because system runs out of memory space give    }  }   void okfunction() {    // try running    while(true)    {        // every time new[] called ptr assigned new address, old not freed        // 90001 ints worth of space reserved on heap        int* ptr = new int[90001]; // never crashes        delete[] ptr; // reserved space above de-allocated     }  } 

why use std::vector? because std::vector internally manages runtime array.

 // allocates  vector(int size) {       // ...       runtimearray = new runtimearray[size];  }   // when vector exits scope deconstructor called , deletes allocated memory  //   not have remember  ~vector() {        // ...       delete[] runtimearray;  } 

so if had same scenario last time

 void vectortestfunction() {    // try running    while(true)    {        std::vector<int> vec(9001); // internally allocates memory    } // <-- deallocates memory here because ~vector called  } 

if want use runtime constant array suggest std:array container. vector in manages internal memory optimized if never need add new elements. declared vector not contain resizing functions after constructor.


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

mapreduce - Resource manager does not transit to active state from standby -

serialization - Convert Any type in scala to Array[Byte] and back -