Baba
Baba

Reputation: 65

Make array in cpp

I am trying to make a new array in my project

the code is:

#include <iostream>
using namespace std;
void makeArray( int *& arrayPtr, int size );
int main( )
{
  int * arrPtr;
  int size =10;
  makeArray( arrPtr, size );
  for(int j=0;j<size;j++)
  {
    cout<<arrPtr[j]<<endl;
  }
}
void makeArray( int *& arrayPtr, int size )
{
  int arr[size-1];
  for(int i=0;i<size;i++)
  {
    arr[i]=0;
  }

  *&arrayPtr=*&arr;
}

According to the requirements i need to use the above "makeArray" method inorder to make the array. When i run the code the output is garbage values not zero.....

any help will be appreciated

thank you

Upvotes: 0

Views: 1134

Answers (3)

Michael Chinen
Michael Chinen

Reputation: 18697

The way you are creating the array is on the stack, which means that it will not exist after the makeArray function finishes.

You will need to allocate the array on the heap.

So:

int arr[size-1];

should be:

int *arr = new int[size-1];

Also, I think you mean to do this in makeArray():

arrayPtr = arr;

Instead of:

*&arrayPtr=*&arr;

Which compiles but is more complex and is functionally the same thing in this context.

But you may prefer just returning an int* instead of taking a reference to the pointer.

Then when you are done using the array in main(), and set it to NULL just in case you accidentally use it again, like this:

for(int j=0;j<size;j++)
{
  cout<<arrPtr[j]<<endl;
}
delete [] arrPtr;
arrPtr = NULL;

Upvotes: 4

uriel
uriel

Reputation: 1248

The "arr" which you allocate in "makeArray()" is local. and when the functione is over the array is release. When you back to main you get garbage. What you want to do, is to use the "new" operator to allocate this new array to be used in all program, unless you will free this memory by "delete". so you can set your makeArray() to:

int* makeArray(int size )
{
  int *arr = new[size];
  for(int i=0;i<size;i++)
  {
    arr[i]=0;
  }

  return arr;
}

the in you main you need to initialize your arry by:

int * arrPtr = makeArray(10);

just don't forget to release this memory after you finsh:

delete[] arrPtr ;

Upvotes: 0

pg1989
pg1989

Reputation: 1010

Why are you declaring a parameter as 'int *& arrayPtr'? Do you just need a pointer to an array? You should use 'int *arrayPtr' instead.

To answer your question, the problem is that you are declaring an array in the function makeArray's stack. Upon the completion of a function, that function's stack is destroyed, so you're passing the address of junk data. To avoid this, use dynamic memory allocation instead.

EDIT: Also, you should use memset instead of a for loop to zero an array. It's much faster.

Upvotes: 0

Related Questions