Skip navigation

I’ve had this question for a while now.

On win32, using Visual Studio, the following program doesn’t work:

#include <stdlib.h>
#include <stdio.h>

void makeArray( char * arr, int dim )
{
  arr = (char *)malloc( dim*sizeof(char) );
}
void printArray( char * arr, int dim )
{
  for( int i = 0; i < dim; i++ )
  {
    printf( "%d ", arr[i] );
  }
}

int main()
{
  char * arr = NULL;
  makeArray( arr, 10 );
  printArray( arr, 10 );
}

You get that arr is still NULL, even after you call makeArray() on it.

However, this does work as expected:

#include <stdlib.h>
#include <stdio.h>

void makeArray( char * & arr, int dim )
{
  arr = (char *)malloc( dim*sizeof(char) );
}
void printArray( char * arr, int dim )
{
  for( int i = 0; i < dim; i++ )
  {
    printf( "%d ", arr[i] );
  }
}

int main()
{
  char * arr = NULL;
  makeArray( arr, 10 );
  printArray( arr, 10 );
}

Using C++’s & to make the variable arr inside makeArray() an alias to the char * pointer that is passed from main.

My question is, why doesn’t the first program work? I just don’t see why it is required to use & when the array should be passed by reference.

Anybody got a clue?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: