c++ - Why does my code produce a segmentation fault? -


#include <iostream> using namespace std;  int main () {     int **a;     int b[5] = {3,4,5,6,1};     *a=b;     cout << *((*a)+0) << endl;     return 0; } 

according understanding *((*a)+0) equivalent (*a)[0]. wrong? how can make above code print first element of array?

and why this code work?

#include <iostream> using namespace std;  int main () {     int *a;     int b[5] = {3,4,5,6,1};     a=b;     cout << *(a+0) << endl;     return 0; } 

when replace a *a everywhere, why wrong?

you access uninitialized pointer in

*a=b; 

at point a points random location, , rule undefined behavior can't predict happen. seems location can't write to, , crash.


the second variant works because make a point b, don't write uninitialized pointer, initialize pointer location of first item in b.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -