Pointers (to pointers) and new/malloc vectors (inside of vectors) c++ -


how pointers work arrays? find syntax bit of mystery, example (16x1):

int* = new int[16]; a[16] = 33; cout << a[16] << endl; 

the above example works. * needs in front of pointer write/read value, not vectors?

the case more complicated multidimensional arrays, found following way create (16x3):

int** = (int**)new int[16]; (int = 0; < 16; i++) {     a[i] = (int*)new int[3]; } a[15][2] = 4; cout << a[15][2] << endl; 

again, above works, it's hard grasp how syntax relates pointers. syntax works malloc. malloc there option "memset" automatically initializes multidimensional array (put in loop). there similar option new?

usually * needs in front of pointer write/read value, not vectors?

you need dereference pointer pointed value. subscript operator way dereference it. a[b] equivalent *(a+b) (unless a class overloaded subscript operator).


int** = (int**)new int[16]; 

this bug. you've allocated array of int, try point first element if int*. if want array of pointers, must specify correct type (int*) in new-expression. way avoid bugs never ever cast return value of new. compiler tell when make mistake.

again, above works

the behaviour undefined.

with malloc there option "memset" automatically initializes multidimensional array (put in loop). there similar option new?

memset in c++ standard library well, don't need initialization. simpler use value initialization. note correct type , lack of casting:

int** = new int*[16](); //                    ^ syntax value initialization 

p.s. don't deallocate memory allocated. therefore leak memory.

p.p.s bad idea store pointeres dynamic objects in bare pointers. it's better use raii container std::vector.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -