c - Typedef struct pointers -


i want pass pointer struct function edit struct.

this not work:

typedef struct{    unsigned char x;   unsigned char y;   float z;   }c_typedef;   c_typedef *ptr_struct;  //this part change work.   void print_typedef(c_typedef *report, unsigned char x_data) {     report->x = x_data;    printf("x equal %d", report->x);   }  int main(void) {      print_typedef(ptr_struct,0x23);     getchar();  } 

now if change part declare pointer still not work. not work:

c_typedef x_struct; c_typedef *ptr_struct; ptr_struct = &x_struct; 

but if change this, work!!

c_typedef x_struct; c_typedef *ptr_struct = &x_struct; 

my question why don't first 2 work? bugging me.

the problem of first version is, didn't allocate memory ptr_struct points to, leads segmentation fault. fixed in:

c_typedef x_struct; c_typedef *ptr_struct = &x_struct; 

that's why third version works. what's wrong second version? because can't assign global variable outside functions, can initialize them did in third version, or should assign in function, in main:

c_typedef x_struct; c_typedef *ptr_struct;  //omit other parts  int main(void) {     ptr_struct = &x_struct;  //here assign pointer value     print_typedef(ptr_struct,0x23);     getchar(); } 

Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -