![]() |
| | #1 |
| Registered User Join Date: Jul 2009
Posts: 2
| problem with pointer to struct It compiles all right, but causes segmentation fault. Here's the code: Code: typedef struct {
int inumber;
float fnumber;
} the_type;
int main() {
the_type* N;
N->inumber = 16; //this line causes segmentation fault - why?
return 0;
}
|
| M9000 is offline | |
| | #2 |
| Registered User Join Date: Sep 2004 Location: California
Posts: 2,845
| You have a pointer to a the_type object. You DO NOT have an actual object -- just a pointer. What does that pointer point to? It points to some random location. You need to assign N to point to a valid object. For instance: Code: the_type* N; the_type O; N = &O; // or... the_type* N = malloc(sizeof(the_type)); |
| bithub is offline | |
| | #3 |
| Registered User Join Date: Jul 2009
Posts: 2
| Thank you. |
| M9000 is offline | |
| | #4 | |
| Mysterious C++ User Join Date: Oct 2007
Posts: 14,099
| This strikes me as odd: you've used C++ before, but this is exactly what would happen in C++, as well. And the solution is exactly the same (except new/delete instead of malloc/free).
__________________ Using: Microsoft Windows™ 7 Professional (x64), Microsoft Visual Studio™ 2008 Team System I dedicated my life to helping others. This is only a small sample of what they said: "Thanks Elysia. You're a programming master! How the hell do you know every thing?" Quoted... at least once. Quote:
| |
| Elysia is offline | |
![]() |
| Tags |
| pointer, struct |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Pointer to struct | Paul Johnston | C Programming | 4 | 06-11-2009 03:01 AM |
| Need help with linked list sorting function | Jaggid1x | C Programming | 6 | 06-02-2009 02:14 AM |
| A problem with pointer initialization | zyklon | C Programming | 5 | 01-17-2009 12:42 PM |
| I'm suppose to use this library but I'm confused on what exactly the data structure | mr_coffee | C Programming | 1 | 12-03-2008 03:10 AM |
| Binary Search Trees Part III | Prelude | A Brief History of Cprogramming.com | 16 | 10-02-2004 03:00 PM |