-4

I am a high school student currently learning C++.So while doing pointers I came across a problem,

first pointer programme

When I try to display the value at y,it shows:Terminal window

The value of x is displayed properly,but after I write *y as *(x+1),it works fine

enter image description here

Can any one please explain why I am getting a segmentation fault?

Despite the what the screenshots show,all the code compiled perfectly.

arkin
  • 111
  • 4

2 Answers2

2

y points to unallocated memory, so dereferencing it is undefined behaviour. You need point it at some valid memory, either by allocating it dynamically, or taking the address of a valid variable, like you did with x.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
1

You set y to x+1. x+1 does not point to an object.

You then try to write data through y. That's not going to work.

It's not at all clear what you are trying to accomplish with this code, so I cannot suggest a remedy.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055