set pointer to null through function

Hi all, i am new in c++. Need your help on the pointer topic.
I want to set my pointer to NULL through function and make sure my main also retains the NULL value. However whenever i print the ptr address in the main it give me a hex value which i assume is the memory location of pointer pointing to. Anyone can point out my errors ? Thanks alot


#include <iostream>

using namespace std;

void a(int *);

int main()
{
int * ptr;
a(ptr);

cout << ptr << endl;
system("pause");


}

void a(int *ptr)
{
ptr = NULL;
}


You are setting 'ptr' parameter to NULL, not 'ptr' in main.
To modify the position pointed by that 'ptr', you should has as argument type a pointer to pointer or a reference of pointer
in C++ terms what bazzy said... :D

1
2
3
4
5
6
7
a(&ptr);


void a(int **ptr)
{
*(ptr + 0) = NULL;
}
You can also try:
1
2
3
4
void a(int*&ptr )
{
    ptr = NULL;
}
But this would be severely weird
*(ptr + 0) = NULL;
Oh, gross.

*ptr=NULL;
Last edited on
1
2
3
4
void a(int*&ptr )
{
    ptr = NULL;
}


I second this method. It's what I would do. It's not weird at all.
Topic archived. No new replies allowed.