Thread: Initialize Data Member in Struct

  1. #1
    young grasshopper jwroblewski44's Avatar
    Join Date
    May 2012
    Location
    Where the sidewalk ends
    Posts
    294

    Initialize Data Member in Struct

    Hello all!

    I was looking at some linked list material and was wondering something. Can you initialize a data member inside a struct like in C++?

    i.e.
    Code:
    typedef struct node
    {
            int data;
            struct node * next = NULL; // this is the line in question
    } LLnode;
    If that is not correct, can someone suggest something?

  2. #2
    young grasshopper jwroblewski44's Avatar
    Join Date
    May 2012
    Location
    Where the sidewalk ends
    Posts
    294
    I think I answered my own question. Is the solution a node-creation function that initializes each data member?

    One more question: if you remove the whole "= NULL" part, did I declare the node-pointer correctely?

    i.e.
    Code:
            struct node * next;
    Last edited by jwroblewski44; 03-28-2013 at 08:21 PM.

  3. #3
    Registered User
    Join Date
    Mar 2010
    Posts
    583
    You can't do it in the struct declaration like in your first post. In C++, a constructor will be called that sets next to NULL. No constructors in C, so... no.

    Quote Originally Posted by jwroblewski44
    I think I answered my own question. Is the solution a node-creation function that initializes each data member?
    Pretty much, yes. If you're using malloc, it'd probably be a good idea to put the call to malloc in there too, then always call that function to create nodes. That way you don't have to remember to call an init() function after creating each node so hopefully will have less risk of uninitialised stuff.

    One more question: if you remove the whole "= NULL" part, did I declare the node-pointer correctely?
    Yep, that's right.

  4. #4
    young grasshopper jwroblewski44's Avatar
    Join Date
    May 2012
    Location
    Where the sidewalk ends
    Posts
    294
    Thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to initialize static const array member of a class
    By nimitzhunter in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2010, 02:15 AM
  2. initialize member array in initializer list?
    By Vick jr in forum C++ Programming
    Replies: 4
    Last Post: 05-20-2010, 06:39 AM
  3. Initialize const member variables in constructors
    By mvgian in forum C++ Programming
    Replies: 5
    Last Post: 03-21-2006, 08:23 AM
  4. using a class as a data member before you initialize the class?
    By class question in forum C++ Programming
    Replies: 6
    Last Post: 01-05-2003, 04:25 PM
  5. Replies: 3
    Last Post: 11-22-2002, 07:08 PM