Thread: Creating instance of a structure

  1. #1
    Registered User
    Join Date
    Apr 2017
    Posts
    11

    Creating instance of a structure

    Hello everyone I am trying to learn C and I am relative new to the language but I did programming in Java before.

    My Problem is I have the following structure

    Code:
    struct FluxCapacitor 
    {
        unsigned char* c_string;
        unsigned int value 
    };
    And now I want to write a function like this

    Code:
    struct FluxCapacitor* createFluxCapacitor()
    In the function I want to create a new instance of my struct and initialize my attributes with random values. Can someone explain to me how to do this in c?

    Thanks for your help !
    Last edited by Jimmy589; 04-05-2017 at 05:51 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,675
    You basically need
    Code:
    struct FluxCapacitor *newfp = malloc( sizeof(*newfp) );
    if ( newfp ) {
      newfp->value = 88; // MPH needed to trigger
    }
    return newfp;
    The caller will need to deal with the possibility that nothing was created (the function returned NULL).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Apr 2017
    Posts
    11
    Well thanks for your help in first place but I need to fill the attributes with random values so canīt I just do it like this

    Code:
    newfp->value = rand();

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,675
    *sigh*

    Try it and find out.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 09-19-2015, 09:42 AM
  2. Creating a class instance (am i going insane?!)
    By JonathanS in forum C++ Programming
    Replies: 3
    Last Post: 12-04-2012, 04:45 AM
  3. Structure tags and instance
    By cjohnman in forum C Programming
    Replies: 2
    Last Post: 05-01-2008, 09:52 AM
  4. creating class instance from a file
    By Callith in forum C++ Programming
    Replies: 1
    Last Post: 11-25-2004, 09:03 PM
  5. creating a new instance of a function?
    By Geolingo in forum C++ Programming
    Replies: 17
    Last Post: 07-18-2003, 09:39 AM

Tags for this Thread