Soban Khan
Soban Khan

Reputation: 19

Null pointer and the address that is null in C++ Visual Studio and gcc compiler

I have tried many tutorials and got more confused. So please teach this noob with simplest answers. If possible then just stick to the question......i am having information overload :)

first the main function

main(){
  int y=0;
  display(&y);
}

Now the function

int display(int* x){
  //do something depending on different values of x
}

One of the case is following: "if no variable is pointed to, that is, if the address of the variable is NULL, your function sets the value of the variable pointed to zero."

Now my understanding in display function i need to do

if (x==NULL)
   *x=0;

Now here is where I am getting stuck with...... - if i call the function with display(NULL); I get following error in Visual "Unhandled exception at 0x00C84036 in BTP 300 A1.exe: 0xC0000005: Access violation writing location 0x00000000."

How do i store some value in y from a function if its address is null?

or the question is just wrong and it should have said value stored at the address, to which pointer variable points, is null i.e y=Null ???

If int* z is a null pointer than what is the value of the address to which z points to and what is the value that is stored in address that is pointed???

Upvotes: 2

Views: 921

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283624

Most likely, this means:

int value_to_display = x? *x: 0;
// do something with value_to_display

i.e., the requirement is to treat a null pointer the same as a pointer to zero.

Upvotes: 2

Thomas Benard
Thomas Benard

Reputation: 210

These two lines won't work :

if (x==NULL)
*x=0;

as you are trying to de-reference NULL which is forbidden.

What you want to do is something like :

if (x==NULL)
    x = new int(0);

Upvotes: 0

Related Questions