Getting segmentation fault with c++ pointers -
so i'm trying familiarise myself c++ pointers running following code.
#include <iostream> using namespace std; int main(void){ int* x; cout << &x << endl; return 0; }
which works fine , prints pointer value of x but
#include <iostream> using namespace std; int main(void){ int* x; *x = 100; cout << &x << endl; return 0; }
gives me segmentation fault when try tun it. why this? don't see how line should change address of x.
and prints pointer value of x but
not exactly.
std::cout << &x;
printsx
's address (the pointer's address);std::cout << x;
prints address,x
points to;std::cout << *x;
printsx
points to;
int* x; *x = 100;
here, x
pointer, need allocate memory 100
. example
int* x = new int; *x = 100; std::cout << *x;
or just
int* x = new int( 100 ); std::cout << *x;
without allocating memory , leaving x
uninitialized, *x = 100
you're trying change random memory, leads undefined behavior.
Comments
Post a Comment