-1

That may well be silly, but I'm going crazy here ..

Why does pTest doesnt point on the new int after test function in main ? It causes seg fault. And how can I do it.

In my real code I need to pass a pointer and dynamically create the object because pTest is a subclass of a virtual class (reading from file so I don't know in advance)

void test(int* pTest)
{
    int *p = new int(2);
    pTest = p;
    std::cout << "pTest : " << *pTest << std::endl;
    return;
}

int main()
{
  int *pTest = NULL;
  test(pTest);
  std::cout << "pTest : " << *pTest << std::endl;

  return 0;
}
user2287453
  • 149
  • 1
  • 8

2 Answers2

2

If you want to mutate value passed as a parameter you have to provide pointer to it. That means if you want to change value of a given int you are passing int* . In your case you want to mutate int* so that you need to pass it as int** instead.

MarekR
  • 2,410
  • 1
  • 14
  • 10
1

you need to pass pTest by reference: void test(int*& pTest) if you want the pTest value to be altered outside the scope of this function.

void test(int*& pTest)
{
    int *p = new int(2);
    pTest = p;
    std::cout << "pTest : " << *pTest << std::endl;
    return;
}
Stephane Rolland
  • 38,876
  • 35
  • 121
  • 169
  • 1
    And instead of providing one of the million dubplicates, that I can't find because I don't know what to search for you make a comment about him not doing so.. – user2287453 Oct 29 '13 at 14:50