I am very new . . . :(

This is a discussion on I am very new . . . :( within the C++ Programming forums, part of the General Programming Boards category; Hello all. I'm very new to C++ and really thought I could use some help with pointers and structures . ...

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    1

    Question I am very new . . . :(

    Hello all. I'm very new to C++ and really thought I could use some help with pointers and structures . . . I am pretty proficient with everything else so far, at least to some degree. But I'm confused as to what the use of a pointer would be to make it more so than just putting the variable in. I'm also confused as to what structures even are. I have read through the tutorials a good amount of times and this is still confusing to me. Help?

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    > But I'm confused as to what the use of a pointer would be to make it more so than just putting the variable in.

    What?

    > I'm also confused as to what structures even are.

    A structure is a type of variable. The contents of a structure is basically a block of memory, some of which has different, smaller variables, inside of it.

  3. #3
    Registered User
    Join Date
    Nov 2003
    Posts
    161
    a pointer is simply an address in memory. Its the same as an address for where you live, and the memory is what is there. For example you can say at address "103 placeName M3M2K4" there's a chuchu train. The address "103 placeName M3M2K4" is the "pointer", one the the things that's there is a chuchu train.

    Same thing with computers except its all numbers and there meaning for example: at address 0x200 is the speed of a chuchu train.
    Code:
    // get the address of how fast the train is moving and store it in variable 'pointer'
    pointer = &chuchu_speed;
    // pass the 'address' to the function to find out when the train will arrive
    // the function will "look up" the address see whats there and calculate
    time = whenWillChuChuArive(pointer);
    Code:
    int whenWillChuChuArive(int* speed){
        // distance the train needs to travel
        int distance = 200;
         // time = distance/speed
         // *speed looks up whats in the address of speed 
         return distance/(*speed);  
    }

    Now for structures lets say we want to supply distance too. First lets do this without structures.

    Code:
    // get the address of how fast the train is moving and store it in variable 'pointer'
    pointer = &chuchu_speed;
    // put the distance beside the speed
    *(pointer+1) = 200;
    // pass the 'address' to the function to find out when the train will arrive
    // the function will "look up" the address see whats there and calculate
    time = whenWillChuChuArive(pointer);
    Code:
    int whenWillChuChuArive(int* speed){
        // distance the train needs to travel
        int distance;
         // distance is the 1 after the address of speed
         // (speed + 1) say's goto beside the address of speed
         // the * say's "what is there?" we define it to be distance
         distance = *(speed+1);
         // time = distance/speed
         // *speed looks up whats in the address of speed 
         return distance/(*speed);  
    }
    The above is good because it touches unwanted memory and is not clear what (speed+1) is unless the persone who wrote it somehow tells you. Instead we define a structure.

    Code:
    struct chuchu {
        int speed;
        int distanceLeft;
    };
    Now we want to use the structure
    Code:
    // declare our train
    chuchu train;
    // set up its variables
    train.speed = 12;
    train.distanceLeft = 200;
    // get the address of train
    pointer = &train;
    
    // pass the 'address' to the function to find out when the train will arrive
    // the function will "look up" the address see whats there and calculate
    time = whenWillChuChuArive(pointer);
    The function below doesn't need anychange since the structure say's "distance will be beside speed". By us placing the "distanceLeft" right after "speed".
    Code:
    int whenWillChuChuArive(int* speed){
        // distance the train needs to travel
        int distance;
         // distance is the 1 after the address of speed
         // (speed + 1) say's goto beside the address of speed
         // the * say's "what is there?" we define it to be distance
         distance = *(speed+1);
         // time = distance/speed
         // *speed looks up whats in the address of speed 
         return distance/(*speed);  
    }
    Lets modify that to use structures so it will be more clear to others
    Code:
    int whenWillChuChuArive(chuchu* whichTrain){
         // whichTrain->X say's "at the address of 'whichTrain' tell whats X"
         // whichTrain->speed say's "at the address of 'whichTrain' tell whats speed"
         return whichTrain->distanceLeft/whichTrain->speed;  
    }

  4. #4
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,171
    An analogy on pointers:
    Memory Functions - Still Learning
    It was written for C, so substitute malloc/calloc with new and free with delete.
    That's basically what they are and how they work.
    The analogy is also following the idea of dynamic memory (building on demand).
    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.
    For information on how to enable C++11 on your compiler, look here.
    よく聞くがいい!私は天才だからね! ^_^

  5. #5
    Registered User
    Join Date
    Aug 2008
    Posts
    15
    Hello Eternalglory47 and good day to you...

    I am just a novice C/C++ programmer so I don't suppose my opinions are really trustworthy, but I have wrote this little discourse
    for you to try and help. Of coarse I wouldn't worry about whether or not these writings are correct because if they are incorrect
    in any way then you can bet that somebody will correct me. Well -- here is some info regarding the statements you made...

    C++ is an object-oriented programming language. As you know C++ has an aspect of it's language referred to as a "class". The C
    language, on the other hand, has a struct. A C struct is different than a C++ class as well as a struct that happens to be
    declared within the C++guidelines. Here are some references for this:


    (1)C struct and C++ struct/class difference

    (2)C struct and C++ struct/class difference


    Although C++ classes and structures have features which C structures do not have -- they are similar in that they each are used
    to declare any number of - different - data types(i.e. int, char, double).

    A class is like a stamp or template. Whenever you use a stamp and create an imprint, the imprint is referred to as an "object"
    or "instance" in C++, and you can create as many imprints or copies as you want. Moreover, in the same way that it is much easier
    to imprint copies of an image with a stamp or template than it would be to painstakingly recreate a copy by hand -- it is also much
    easier to simply create a bunch of variables just by typing one short class name(type identifier) and an instance of that type
    rather than typing out every single variable again and again. Classes can also be thought of as a blueprint, and an object can be
    thought of as what is actually built based on those blueprints.

    A class has a few main purposes:
    ================================================== ==========================================
    (1) ORGANIZATION:

    They allow programmers to group - related - data(i.e. variables) and functions(called methods if put inside a class) together
    under - one - main title. For example the words truck, car, boat,plane can be considered related, and so you might want to
    - group - them together under one main title such as "Transportation". Likewise the variables
    Code:
    float truck;
    int car;
    char boat;
    char plane[20]; //char array with 20 elements
    ...might make more sense to group them together under one main title within a class. For example:
    Code:
    #include <iostream>//C++
    //#include <stdio.h>//C
    
    using namespace std;
    
    class  Transportation
    {
        float truck;
        int car;
        char boat;
      
        public: 
             char plane[20];
    };
    
    int main()
    {
         Transportation TransportationObject;
    
          TransportationObject.plane[0]='H';
          TransportationObject.plane[1]='e';
          TransportationObject.plane[2]='l';
          TransportationObject.plane[3]='l';
          TransportationObject.plane[4]='o';
          TransportationObject.plane[5]='\0';
    
          cout <<  TransportationObject.plane;
          getchar();
          return 0;
    }
    - Classes allow you to organize data. Please understand that many programs can become very very large, and can be divided among
    many files, and so organization then becomes very necessary. You can find the same need for organization in any office's file
    cabinet in the world.

    --------------------------------------------
    (2) INFORMATION HIDING and distinguishing and also ENCAPSULATION:

    - Classes allow a group of programmers to hide data from one another. See, in general you can not use the same name for multiple
    variables or functions within the same program or more specifically – within the same scope(i.e. {}). However, there may be a
    -group- of programmers working on separate pieces of a single program, and naturally they will need to use a name that maybe
    another programmer has already used. It then becomes necessary to use classes to hide or distinguish those same names from each
    other. Classes are one of the ways to use the same name more than once.

    Classes also allow programmers to change or update their code in the future more easily. Programmers can design code within
    their class or directly associated with their class in such a way that if something in their class needs to be changed or updated
    they will more easily be able to make the necessary changes or updates without affecting the rest of their code in an
    - unexpected - way, and as I would imagine you know, professional programs are constantly being updated or improved. Other
    programmers may want to use the classes that a certain programmer makes, but they may want to make a few changes to better
    suit their needs. There are many aspects to this type of design process, but the aspect that I am particularly pointing out is
    Encapsulation. Encapsulation helps programmers to make changes to their code and the changes are encapsulated or
    restricted to only a small part of their program.

    I suppose one way to look at it is -- have you ever seen a movie where a group of people within a building or area are assumed
    to have been infected with a very deadly, and contagious disease?Well you know how the Center for Disease Control steps in, and
    quarantines everybody in order to keep the disease from spreading? Well by encapsulating or quarantining the members within a struct
    or class, using a feature such as polymorphism, you can control the effect it would have on the rest of your program outside of that
    class or struct -- if you or another programmer decide to change your code a bit or apply it to a new implementation.. The language
    features that have been established for or associated with C++ classes that would particularly be associated with encapsulation and
    also information hiding and distinguishing are friendship, inheritance,polymorphism, namespace, the keywords private and protected,
    and lastly a class just by itself IS encapsulation, although the other features build on the definition of encapsulation.

    Here is a link that explains what I just said only more accurately, specifically, and in more detail (Information hiding).


    This is a definition of encapsulation and this is someone else's opinion of encapsulation and also their objection tothe definition given at the
    previous link.

    --------------------------------------------
    (3) CONVENIENCE of CREATING:

    - If you did not create objects(copies) of a class then you would have to meticulously type every single variable contained within
    that class that you plan on using. Larger programs can use many many variables. You also can create or delete objects dynamically
    while a program is running. Deleting objects saves space, and improves efficiency, and that is extremely important!!! Many programs
    will actually - need - to dynamically create and delete a series of variables over and over, and so in these cases there is no way
    of knowing how many variables a program would need. Dynamically creating a structure or class, which can contain many different
    variables, is easy because you only need to refer to - one single – identifier which represents many variables. Here are a few
    random links to some examples of dynamically creating classes and structures in C/C++.

    (1) Dynamic memory
    (2)Dynamic memory

    ---------------------------------------------------
    (4)CONVENIENCE of ACCESSING :

    - Classes and structures can be placed inside an array and each member can be accessed in a continuous or sequential fashion
    -- where only the number contained within the array subscript need be changed. Because - only - the number within the array need
    be changed a programmer only needs to type the paths in which he/she accesses the members of a class, and the computer
    itself will make all the other changes. Here is an example of what I mean:
    Code:
    #include <iostream>
    
    using namespace std;
    
    class TypeofClass
    {
        public:
           int a;
           int b;
           int c;
    
           char d;
    };
    
    int main()
    {
       TypeofClass ObjectofTypeofClass[300];//This declaration creates 300 copies(objects)of "TypeofClass"
    
       int intA=0, intB=0, intC=0;
       char charD;
    
       cout << "Enter a number for int a:";
       cin >> intA;
    
       cout << "Enter a number for int b:";
       cin >> intB;
    
       cout << "Enter a number for int c:";
       cin >> intC;
    
       cout << "Enter one character for char d:";
       cin >> charD;
    
      //This loop increments the variable "i" by one each pass.
      // ObjectofTypeofClass[0] is the first copy of  TypeofClass out of 300 copies, and
      // ObjectofTypeofClass[0].a is an attempt to access the "int a" contained within copy number 0.
      //The beginning of an array is actually 0 and not 1.
      //ObjectofTypeofClass[299] is the very last copy of TypeofClass that I created above.
    
        for(int i=0; i < 300; ++i)
       {
          ObjectofTypeofClass[i].a = intA;
          ObjectofTypeofClass[i].b = intB;
          ObjectofTypeofClass[i].c = intC;
          ObjectofTypeofClass[i].d = charD;
       }
    
       for(int i=0; i < 300; ++i)
       {
          cout << ObjectofTypeofClass[i].a << endl;
          cout << ObjectofTypeofClass[i].b << endl;
          cout << ObjectofTypeofClass[i].c << endl;
          cout << ObjectofTypeofClass[i].d << endl;
       }
    
       return 0;
    }
    Of course this is not the idea example for assigning values to the members within an array - of objects, but it is a simple
    demonstration however. Linked list or STL containers would be a better approach.

    ------------------------------------------------------------------------------------------------------------------------------
    Classes also have two features which are known as a constructor and a deconstructor. A constructor is used to construct the
    values of an object when an object is created and a deconstructor is used to deconstruct the values of that object when that object
    is deleted. A contructor and deconstructor are like functions that were specifically developed, as part of the C++ language, just to be
    used with classes. Their particular role in C++ is to initialize the values within an object and perform any other tasks that - you want -
    to be performed whenever an object gets created(whatever those tasks may be). A contructor gets called and executed at the
    point of itss -- creation.

    A deconstructor is like a constructor except its purpose is to - delete - the values within the object I just mentioned, and
    perform any other tasks that you want performed when the object gets deleted.

    An object's constructor is automatically called --- when --- it comes into scope(i.e. {}).An object's deconstructor is
    automatically called --- when --- it falls out of scope. Variables in C++ can be declared between, I suppose, any set of curly
    braces. Braces create scope. You -- have to set up the processes necessary within a constructor and deconstructor in order to do
    anything that I just mentioned.

    A variable or object variable is created at the place of its declaration between a - pair - of curly braces. It is created when
    the computer gets around to reading that part of your program. A variable or object variable is deleted when the program reaches
    the matching curly brace.
    -------------------------------------------

    Lastly, I should point out the syntax that class and structs use to access their members. So here is an example of a nested
    structure(a nested structure is a stucture inside another structure.)
    Code:
    #include <iostream>
    using namespace std;
    struct struct1
    {
       int a1;
       int b1;
       int c1;
       char d1[20];
    };
    struct struct2
    {
       int a2;
       int b2;
       int c2;
       struct1 struct1Object; /*Here I declared a struct1 object called struct1Object that is inside - this - struct2
                                 structure template.*/
    };
    int main()
    {
        struct2 struct2Object; //Here I create a copy(object) of struct2 which is called struct2Object
        strcpy(struct2Object.struct1Object.d1, "012345");
        cout <<  struct2Object.struct1Object.d1; /*Here I open up struct2Object then struct1Object then the d1 char array, and I 
                                                    access the letters that I put inside the array d1 with strcpy()*/
        return 0;
    }
    Think of accessing the members of a struct or class like opening up folders on Windows Operating system. A folder can contain files
    or other folders -- And those folders can also contain files or other folders, and so on...... Now all those folders and files have
    a directory path, and as you probably know, the directory path uses the backslash(i.e. "\") to separate the names of all the files
    and folders within a path(e.g. "C:\Users\JIMMY\Documents"). In order to access a char array that is within a struct that is itself
    also within another struct you have to create a type of directory.

    The dot operator "." is like the backslash. It is the C/C++ way to create a kind of directory and access the contents within a
    class or struct. There are of coarse other ways to access the contents.
    ================================================== ================================================== ==[
    Last edited by JimmyJones; 09-05-2008 at 05:20 PM.

  6. #6
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,171
    Lots of information there, but I would like to point out some things.
    First:

    Quote Originally Posted by JimmyJones View Post
    ================================================== ==========================================
    (1) ORGANIZATION:

    They allow programmers to group - related - data(i.e. variables) and functions(called methods if put inside a class) together
    under - one - main title. For example the words truck, car, boat,plane can be considered related, and so you might want to
    - group - them together under one main title such as "Transportation". Likewise the variables
    Code:
    float truck;
    int car;
    char boat;
    char plane[20]; //char array with 20 elements
    ...might make more sense to group them together under one main title within a class. For example...
    This is not the purpose of a class.
    A class's purpose is to act as a blueprint to an object - a model of reality. It can be a car, a store, a plane, but it's not a collection of variables and functions. It's an object that contains whatever is necessary to make that object or model work.
    Organizing and grouping data is better done with namespaces.

    (2) INFORMATION HIDING and distinguishing and also ENCAPSULATION:
    This isn't quite it either.
    Look at it like this. We have stores all around us. Now pictures those stores as objects.
    You buy something from there, or sell, using the objects public interface. You don't know what's going on behind the scenes.
    And you don't need to know what's going on behind the scenes to make it work either. And if the store decides to update their internal system and workings, it still doesn't matter, because you can still buy and sell as usual with no changes.
    This is encapsulation. The workings of the object can change, but it won't break the code that's using the object.

    Classes also have two features which are known a as a constructor and a deconstructor. A constructor is used to construct the
    values of an object when an object is created and a deconstructor is used to deconstruct the values of that object when that object
    is deleted. A contructor is like a function that was specifically developed, as part of the C++ language, just to initialize the
    values within an object and perform any other tasks that -you want - to be performed whenever an object gets created(whatever those
    tasks may be). A contructor gets called and executed at the point of its -- creation.

    A deconstructor is like a constructor except its purpose is to - delete - the values within the object I just mentioned, and
    perform any other tasks that you want performed when the object gets deleted.

    An object's constructor is automatically called --- when --- it comes into scope(i.e. {}).An object's deconstructor is
    automatically called --- when --- it falls out of scope. Variables in C++ can be declared between, I suppose, any set of curly
    braces. Braces create scope. You -- have to set up the processes necessary within a constructor and deconstructor in order to do
    anything that I just mentioned.

    A variable or object variable is created at the place of its declaration between a - pair - of curly braces. It is created when
    the computer gets around to reading that part of your program. A variable or object variable is deleted when the program reaches
    the matching curly brace.
    I also would like to point out that a constructor initializes an object and a destructor deinitializes it. This doesn't just mean creating and preparing variables.
    Say for example a car.
    The constructor would create a car, build it from scratch, assemble the components and make it ready to receive you and run.
    The destructor would pick it apart piece-by-piece until nothing was left.
    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.
    For information on how to enable C++11 on your compiler, look here.
    よく聞くがいい!私は天才だからね! ^_^

  7. #7
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    Well Jimmy, don't count yourself out. A good way to learn is to help others truly understand a concept. Its a good idea, however, to do your absolute best to only post information that you know for sure is accurate and not in need of correction. People will be there to jump over your mistakes, but rarely is it done without a certain level of hostility and arrogance.

    On an entirely different subject. I know a Jimmy Jones.... So your name kind of through me off.

Popular pages Recent additions subscribe to a feed

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