Introduction to Computer Science - C++

Using New in a function

You might want a function to get a pointer and for the function to create an array that that pointer will point to. To do this, the function must receive a reference to a pointer (or a pointer to a pointer). This is so that any changes made to the pointer in the function will affect the real pointer and not merely the copy of the pointer. The following first attempt is close but won't work.

      #include
      using namespace std;


      void foo(  char ** vec) {
      *vec = new char[10];
      *vec[0] = 'a';
      *vec[1] = 0;
      }

      int main()
      {
      char * ptr;
      foo(&ptr);
      cout << ptr;
      system("pause");
      return 0;
      }
  
There's an order of operator issue here on the dereferencing of *vec[] . Surround *vec with parenthesis and it will work. Below is a modified version with a couple of other minor changes too. See precedence table here where array subscripting is at level 1 and dereference is at level 2.

Here is a fix:



      #include
      using namespace std;


      void foo(  char ** vec) {
      *vec = new char[10];
      (*vec)[0] = 'a';
      (*vec)[1] = 0;
      }

      int main(int argc, char** argv)
      {
      char * ptr;
      foo(&ptr);
      cout << ptr << endl;
      system("pause");
      return 0;
      }
		      
  
But this is ugly. We can make the code cleaner and clearer to read and do ourself (or whoever) a favor by creating a new pointer in cases like this. We spare ourself - and anyone who reads your code - the confusion.

Here is a better version of the function:


void foo(  char ** vec) {
*vec = new char[10];
char* str = *vec;
str[0] = 'a';
str[1] = 0;
}