c - Allocating a pointer by passing it through two functions -


What am I doing wrong here? Am I assigning memory to the original charPtr or something else? Why can I read the value of func2 inside charPtr , but main ( charPtr is NULL in the main)?

  #include & lt; Stdlib.h & gt; # Include & lt; Stdio.h & gt; Zero func2 (char * charPtr) {charPtr = (four *) molk (size (four)); * CharPtr = 'c'; Printf ("func2:% c \ n", * charPtr); } Zero func1 (four ** charDoublePointer) {// * charDoublePointer = (four *) malloc (sizeof (char)); Func2 (* charDoublePointer); } Int main (int argsc, char * argv []) {char * charPtr = NULL; Func1 (& amp; charPtr); Printf ("% c \ n", * charPtr); }  

You are losing a level indirection func2 Take the TI to four ** like func1 . When you type:

  void func2 (char * charPtr) {charPtr = (four *) malloc (sizeof (char)); * CharPtr = 'c'; Printf ("func2:% c \ n", * charPtr); }  

You are just assigning local variable charPtr , which has no effect on external program. Instead, type:

  void func2 (char ** charPtr) {* charPtr = malloc (sizeoff (four)); // malloc ** charPtr = 'c'; Printf ("func2:% c \ n", ** charPtr); }  

Change the name to charDoublePtr if you insist.

and call it at func1 : like:

  func2 (charPtr);  

Comments

Popular posts from this blog

winforms - C# Form - Property Change -

javascript - amcharts makechart not working -

java - Algorithm negotiation fail SSH in Jenkins -