-1

I have a little problem. Why does (1) show me "p[0]=1" but (2) doesn't show me anything.Looks like you can't dynamically allocate the pointer outside of the main which seems odd to me, is that the case?

/////////
// (1) //
/////////

#include <iostream>

int main()
{
    int *p = nullptr;
    p = new int[4];
    p[0] = 1;
    printf("p[0]=%X", p[0]);
    return 0;
}

// OUTPUT: p[0] = 1
/////////
// (2) //
/////////

#include <iostream>

void init(int *p)
{
    p = new int[4];
    p[0] = 1;
}

int main()
{
    int *p = nullptr;
    init(p);
    printf("p[0]=%X", p[0]);
    return 0;
}

// OUTPUT:
Unknowxxx
  • 1
  • 1
  • 1
    Pointers are only addresses. Those addresses are passed by value; the `p` in `main` is never modified in the second snippet what's modified is a copy of the address. You'd need to change the parameter type to a reference to the pointer to change this: `void init(int* &p) { ... }` – fabian May 20 '22 at 17:38
  • I know there is a duplicate for this, but in short, you are passing the pointer by value. It is no different than this: `void foo(int x) { x = 10; } int main() { int x = 0; foo(x); }` you will see that `x` is still 0 in `main` after `foo` is called, not 10. Now ask yourself why, and that is the reason why that pointer value didn't change. – PaulMcKenzie May 20 '22 at 17:39

0 Answers0