Thread: problem with pointer to struct

  1. #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;
    }

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    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));

  3. #3
    Registered User
    Join Date
    Jul 2009
    Posts
    2
    Thank you.

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    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).
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointer to struct
    By Paul Johnston in forum C Programming
    Replies: 4
    Last Post: 06-11-2009, 03:01 AM
  2. Need help with linked list sorting function
    By Jaggid1x in forum C Programming
    Replies: 6
    Last Post: 06-02-2009, 02:14 AM
  3. A problem with pointer initialization
    By zyklon in forum C Programming
    Replies: 5
    Last Post: 01-17-2009, 12:42 PM
  4. Replies: 1
    Last Post: 12-03-2008, 03:10 AM
  5. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM

Tags for this Thread