jcampos12
jcampos12

Reputation: 55

Using a pointer to an array to fill dynamic array

I want to pass an array to a constructor and use its elements to fill in a dynamic array. However, I cannot understand how to go about using this array in the constructor.

I have made a function that returns a pointer to this array but I cannot use it inside the constructor for the object I am trying to create.

struct PCB
{
   private:
   int * ptr;
   public:
   PCB(int * array)
   {
      ptr=new int[3];
      for(int i=0;i<3;i++)
      {
         *(ptr+i)=*(array+i);
      }
   }
};

int * returnPtr()
{
   int blockArr[]={21,2,3};
   return blockArr;
}

int main()
{
   PCB * pcb=new PCB(returnPtr());
}

This code gives me a "segmentation fault" error using visual studio code. I simply want to be able to copy the elements of the array into the dynamic array. Where have I messed up?

Upvotes: 1

Views: 79

Answers (2)

stylo
stylo

Reputation: 506

You declared blockArr as a local memory, and it will be deleted once you get out of returnPtr function. allocate byteArr as just as you allocated ptr.

int blockArr = new int[3];

Upvotes: 1

Eduardo Pascual Aseff
Eduardo Pascual Aseff

Reputation: 1166

Try this

struct PCB
{
   private:
   int * ptr;
   public:
   PCB(int * array)
   {
      ptr=new int[3];
      for(int i=0;i<3;i++)
      {
         *(ptr+i)=*(array+i);
      }
   }
};

int main()
{
   int blockArr[]={21,2,3};
   PCB * pcb=new PCB(blockArr);
}

It should fix the "segmentation fault". And remember create a destructor.

Upvotes: 1

Related Questions