c++ - Simple code regarding code to read from a struct pointer -


i'm trying understand pointers did code:

#include<iostream>  using namespace std;  struct teste{   int a;   bool b; };  void (struct teste* a) {   cout << (*a).a << (*a).b << "\n"; }  int main() {   teste* e;   (*e).a=2;   (*e).b=0;   say(e); } 

which gives me segmentation fault

but following:

#include<iostream>  using namespace std;  struct teste{   int a;   bool b; };  void (struct teste* a) {   cout << (*a).a << (*a).b << "\n"; }  int main() {   teste e;   e.a=2;   e.b=0;   say(&e); } 

i know second 1 prefered why first 1 not work? think did right.

imagine ask me "where airport"? offer write address of on sticky note you.

on note write:

airport 

this not helpful, it?

teste* e; 

this says "declare variable, e, such holds address of instance of teste in memory".

but haven't provided actual instance of teste point to; didn't assign address of it.

int main() {     teste instance;     teste* e = &instance;     e->a = 2;     (*e).b = 0;  // equivalent e->a     say(e); } 

the line

teste* e = &instance; 

says "declare variable, e, such holds address in memory of teste struct, , let address address-of instance (&instance)".

we have written

teste* e; e = &instance; 

but it's better practice try , initialize variables @ time of declaration, if can.

the -> operator more-or-less syntactic sugar (*e). -- accesses through (dereferences) pointer.

e->a // equivalent (*e).a 

where . member-of -> member-through.

note . , -> distinct operators, become important later in understanding of language.

in example, instance local variable , created on stack. means when scope ends destroyed/go away.

if need instance stick around longer, or large, can allocate "heap".

int main() {     teste* e = new teste;     e->a = 2;     e->b = 0;     say(e);     delete e; } 

explaining new , delete beyond scope of answering question, leave learn them , use.


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -