C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 07-30-2009, 03:18 PM   #1
Registered User
 
Join Date: Jul 2009
Posts: 2
problem with pointer to struct

Hi, I'm new to C, I've only used C++ before. I have this problem with pointers to struct. This seems really elementary but I just can't find the solution.
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   Reply With Quote
Old 07-30-2009, 03:23 PM   #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   Reply With Quote
Old 07-30-2009, 03:31 PM   #3
Registered User
 
Join Date: Jul 2009
Posts: 2
Thank you.
M9000 is offline   Reply With Quote
Old 07-31-2009, 11:23 AM   #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:
Originally Posted by cpjust
If C++ is 2 steps forward from C, then I'd say Java is 1 step forward and 2 steps back.
Elysia is offline   Reply With Quote
Reply

Tags
pointer, struct

Thread Tools
Display Modes

Forum Jump

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


All times are GMT -6. The time now is 12:33 AM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 RC2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22