creating and using a structure

Discussion in 'Information Technology' started by ballurohit, Feb 26, 2012.

  1. ballurohit

    ballurohit New Member

    Joined:
    Nov 18, 2011
    Messages:
    43
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    retired
    Location:
    Gujarat
    I just reproduce the example

    #include <iostream.h>
    struct student
    {
    int stnumber;
    char *stname;
    char *stsex;
    };
    int main()
    {
    student stu;
    return 0;
    }
     
  2. ballurohit

    ballurohit New Member

    Joined:
    Nov 18, 2011
    Messages:
    43
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    retired
    Location:
    Gujarat
    I do not understand using structure. So kindly advice how to use it
    in C++.
     
  3. ballurohit

    ballurohit New Member

    Joined:
    Nov 18, 2011
    Messages:
    43
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    retired
    Location:
    Gujarat
    I do not understand using structure. So kindly advice how to use it
    in C++.
     
  4. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    0
    Trophy Points:
    0
    to access the structs' members, use the . notation.

    Code:
    stu.stnumber = some_value;
    
    Code:
    struct student {
        char *stname;
        char *stsex;
        int stnumber;
    };
    
    struct student stu;
    you've got the same issue as with the other topic regarding char *... they're pointers that point to nothing; if you try to use them that way, you'll likely crash your program. to use them to hold data, you need to allocate some space or assign them to an existing char array[some_size].

    Code:
    stu.stname = new char[20]; // allocate some space
    stu.stsex = new char[10]; // allocate some space
    // do something with stu.stname
    // do somehting with stu.stsex
    delete [] stu.stname; // clean up memory allocated
    delete [] stu.stsex; 
    
    if you don't really understand new and delete right now, then create two static arrays for stname and stsex.

    Code:
    struct student {
       char stname[20];
       char stsex[10];
       int stnumber;
    };
    
    struct student stu;
    
    or
    
    typedef struct {
       char stname[20];
       char stsex[10];
       int stnumber;
    } student;
    
    student stu;
    
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice