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():

  1. a declared in main.
  2. a passed value (because there's no other way) func.
  3. the a in func assigned to.
  4. func returns. a destroyed (leaking memory), , main's a left uninitialised.
  5. ???
  6. main tries use a. segfault!

there few possible solutions here:

  1. 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);     ... } 
  2. do c++ way: pass reference.

    void func(int **&a, int x, int y) {     //          ^     // change. neat! 
  3. 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

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -