-
Structures and floats
I'm using an UNIX os, the schools, and I'm having trouble literally assigning a value to a structure variable.
Here's the simple code...
#include <stdio.h>
structure example
{
float gpa;
};
typedef struct example Example;
Example number;
int main()
{
number->gpa = 5.65;
return 0;
}
It complies, but when I run it, I get Segmentation fault (core dumped)..
Why does this happen? Please help.
Josh
-
Use the dot operator rather than the arrow ->
The arrow is a shorthand way to derference an object. You did not define a pointer to the structure so you do not require using the arrow.
-
Since the structure only has one variable (float gpa) why not just do something like this:
Code:
typedef unsigned float GPA; /* its unsigned since a gba isn't negative*/
GPA grades = 0.01;
-
Firstly, I think that except for C++, you must use the "struct" keyword to declare a new one of a certain type. Also you may omit one layer of that declaration:
typedef struct example
{
float gpa;
};
struct example number;
Second you are using pointer notation to access a struct, not a pointer to a struct.
printf("/"number/" GPA data is %.2f...\n", number.gpa);
Good Luck!
-
Oops... I made a typo in my initial code...
it was supposed to be Example* example.
That's why I'm so bothered... because it crashes on a very simple application.
Josh
-
remembe a pointer points to memory.
try this
int main()
{
Example ex;
number = ex;
number->gpa = var;
return 0;
}
-
> it was supposed to be Example* example.
Whenever you have a pointer variable, it is YOUR responsibility to make sure it points somewhere. Judging from your initial post, this will be a global variable, and thus be initialised to the NULL pointer (this pretty much guarantees a segfault on *ix operating systems).
Example *number; // your uninitialised pointer
....
Example foo;
number = &foo; // point at variable of the same type
or
number = malloc( sizeof(Example) ); // dynamically allocate
Then you can do number->gpa stuff without problems.