Initialize Array of Pointers by Reference C++ -
basically trying initialize array within function, segfaults:
void func(int **a, int x, int y) { = new int*[x]; (int i=0; i<x; i++) a[i] = new int[y]; } void main() { int **a; func(a, 2, 3); }
however if init array outside function pass it, works perfectly, can assign values / print them. i'm struggling passing reference of array don't have init outside function.
void func(int **a, int x, int y) { (int i=0; i<x; i++) a[i] = new int[y]; } void main() { int x = 2; int **a = new int*[x]; func(a, x, 3); }
what's biting here c's (and c++'s) lack of by-reference argument passing. a
in main()
distinct a
in func()
:
a
declared inmain
.a
passed value (because there's no other way)func
.- the
a
infunc
assigned to. func
returns.a
destroyed (leaking memory), ,main
'sa
left uninitialised.- ???
main
tries usea
. segfault!
there few possible solutions here:
do classic c way: pass pointer value. in case, parameter
int ***a
, gettng little ridiculous, whatever.void func(int ***a, int x, int y) { *a = new int*[x]; (int i=0; i<x; i++) (*a)[i] = new int[y]; } int main(int argc, char **argv) { ... int **a; func(&a, 2, 3); ... }
do c++ way: pass reference.
void func(int **&a, int x, int y) { // ^ // change. neat!
do proper (in opinion) way: return value function, , initialise array that.
int **func(int x, int y) { int **a = new int*[x]; // edit: fixed stupid typo bug // existing code return a; } int main(int argc, char **argv) { ... int **a = func(2, 3); ... }
Comments
Post a Comment