1

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?

2
  • The problem is that the memory of the array is freed after the execution of the function returnPtr. Commented Sep 15, 2019 at 4:51
  • Why are you using low level pointers? Why not just use std::vector and std::array? Commented Sep 15, 2019 at 5:03

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi thanks for the feedback. Is it possible to achieve this without getting rid of the function "returnPtr"?
well, there several approaches, one is using static int blockArr[]={21,2,3};, so the memory will remain as long as the program do
other way is declare the array in the global scope, but I don't like it that way
1

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];

1 Comment

blockArr was declared as local memory, no static. If were static there were no problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.