[Solved] Using “->” instead of “.” to access structure gives Segmentation Fault


somestruct *mystruct defines a pointer to memory of type somestruct and does not point to anything, or better if it is local variable then it is not initialized and this is Undefined Behaviour.

If you do this somestruct mystruct then you define struct itself and not a pointer (object exists in memory).

To use pointer access, you should reserve memory for your struct like:

somestruct *mystruct = malloc(sizeof(*mystruct));
mystruct->variable = 5;

Or you can also do this:

somestruct mystruct; //Create my structure in memory
somestruct *mystruct_ptr = &mystruct; //Create pointer to that structure and assign address
mystruct_ptr->variable = 10; //Write to mystruct using pointer access

solved Using “->” instead of “.” to access structure gives Segmentation Fault