c++ - Access violation on pointer -


in code, trying convert decimal number binary. (yes, aware such function exists -- trying reinvent wheel exercise.) because using function tobinnum() convert number, wanted pass empty array reference, store binary digits in array, , upon returning main() function, have array binnum. not happen; pass pointer, initialize , store binary digits, when return main() , attempt access pointer, fails, issuing "access violation on pointer" error. assuming memory being freed up, although can't figure out why, given scope of pointer in main(), , new keyword used in tobinnum() when created array inside it. why isn't working, , how can fix it?

#include <cmath> #include <iostream> using namespace std;  void tobinnum(int, int*, int&);  int main(){     int* binnum = nullptr; //binnum hold array of binary digits     int binnumsize;     tobinnum(100, binnum, binnumsize);      int numones = 0;     (int j = 0; j < binnumsize; j++){         if (binnum[j] == 1) //error.             numones++;         cout << binnum[j];     }     cout << numones;      cin.get(); }  /*void tobinnum(). converts decimal number binary.  parameters:      binnum int pointer value null, tobinnum() use pointer store int array of 0s , 1s generates (each index hold binary value).     binnumsize int, holds length of binnum array use in other scopes     decnum int, decimal number converted binary. */ void tobinnum(int decnum, int* binnum, int& binnumsize) {     binnumsize = int(log2(decnum)) + 1; //how many digits binnum be?     binnum = new int[binnumsize];     int factor = pow(2, binnumsize - 1); //what largest 2^n should start dividing decnum by?      //find 1s , 0s binary array     (int j = 0; factor >= 1; j++){         if (decnum / factor > 0){             binnum[j] = 1; // 1 1 0 0 1             decnum %= factor; //100   36   4   0         }         else             binnum[j] = 0;         factor /= 2;  // 64   32    16   8   4   2     }      //output each index of binnum. confirmation function works.     (int j = 0; j < binnumsize; j++)         cout << binnum[j] << endl;  } 

pass pointer reference

void tobinnum(int, int* &, int&); 

in c can use 1 more indirection

void tobinnum(int, int**, int*); 

the problem function declaration parameter not passed reference (though reference local variable of function) local variable of function destroyed after exiting function. changes of local variable not influence on original argument.

you can imagineg function call following way. lets's assume have function declared like

void f( int *p ); 

and call following way

int main() {     int *q = nullptr;      f( q );      //... 

then function definition can imagined like

void f( /* int *p */ ) {     int *p = q;      p = new int;      //... 

as see argument q not changed. local variable p got new value.


Comments