Results 1 to 3 of 3

Thread: Pointers C/C++ *Brandon Help!!

  1. #1
    Join Date
    Dec 2011
    Location
    -bash
    Posts
    515
    Mentioned
    0 Post(s)
    Quoted
    27 Post(s)

    Question Pointers C/C++ *Brandon Help!!

    Need help understanding pointers. Someone* explain please what they do and how they can be used in a program.

  2. #2
    Join Date
    Feb 2011
    Location
    The Future.
    Posts
    5,600
    Mentioned
    396 Post(s)
    Quoted
    1598 Post(s)

    Default

    C++ posts tonight I see lol.

    Well lets start. Lets say you want to allocate a buffer to hold some data. You do not know the size of the amount of data it will hold and it is determined by some function during runtime.

    A pointer to the buffer is the answer. We have no other way of accessing a dynamically allocated array or buffer other than using a pointer.

    So what is a pointer? A pointer is exactly what it's name suggests. It will point us to the location in memory where our data is OR where our memory is allocated.

    There's a difference between references and pointers. Lets clear that up now.

    The first we will speak about is the reference variable which is preceded by the Ampersand sign (&).

    C++ Code:
    void ChangeValueOfX(int &SomeValue)
    {
        SomeValue = 10;        //We have the address of X so lets change the value at that address from 5 to 10.
    }

    int main()
    {
        int X = 5;
        ChangeValueOfX(X);        //X was passed by reference.
    }

    In the above, we got the address of X from the referencing parameter. We changed the value at that address to 10. Thus X is no longer 5 but it is 10.

    Now to what we call pointers. A pointer is like a direction sign that you see in the streets telling you to go this way or that. A pointer will hold the address given to it/Point you to the location in memory of a variable, datatype, anything! Pointers can be tricky at first but after about 2-3 days of practicing hands on, you will get it for sure!

    A pointer can point to the address of a variable or memory location as said before, but not only that, it can point to arrays as well. When a pointer to an array is declared, it will always start off as pointer to the address of the first cell in the array.

    Example:
    C++ Code:
    char Buffer[5] = {'a', 'b', 'c', 'd', 'e'};
    char *P = B;   //P will point you to the address in memory where 'a' is located. Aka Buffer[0].

    Pointers can be added and incremented just like normal operators/mathematically. Thus you can make a pointer point to the next cell's address by doing PointerName++. Since pointers usually hold the address of a memory location which is usually either given to it by the user via &variable or given to it by a function, we introduce dereferencing a pointer. To dereference a pointer, we use the * operator. This will give us the value pointed by our pointer.

    Example:
    C++ Code:
    int A[5] = {1, 2, 3, 4};
    int *P = &A;   //We declare a pointer called P and make it point to the address of A[0];

    cout<< *P <<endl;   //This will print A[0] aka 1. This is because we derefenced our Pointer inorder to get the value of A[0].
    //We can also change the value of A[0] using the same method.

    *P = 9000;   //Now A[0] will have a value of 9000. We dereferenced out pointer to access the value of Cell A[0] and change it indirectly.

    Lets see a practical use of a pointer for file operators and buffer operations:
    C++ Code:
    int SizeOfFile(File* pFileHandle)
    {
        //Some code to determine file size..
        return FileSize;
    }

    int main()
    {
        char Buffer[100];    //Create a char array buffer of a static size of 100. We know the size here.
       
        fread(&Buffer, 1, 100, PointerToAFileHandleHere);    //Our Buffer now gets filled with the data from some file that we read. Note that we had to pass Buffer by reference. AKA it's address to fread so that it can fill the buffer.
       
        //Lets suppose that we do not know the size of this file. How do we know how large to make the buffer?
       
        char* pBuffer = new char[SizeOfFile];    //DYNAMICALLY allocate a buffer and return the pointer to it!
        //In the above, pBuffer is a pointer to the memory location where we allocated a large enough amount to hold our file.
        //new char[SizeOfFile] allocated a buffer and assigned it's pointer to pBuffer.
       
        //The only way we can now fill the memory with data from a file is through that pointer aka. pBuffer.
       
        int FileSize = SizeOfFile(pFileHandle);
        fread(pBuffer, 1, FileSize, pFileHandle);  //Note that there is no address operator because pBuffer is already a pointer and it pointers to the address where it allocated memory. Thus the memory at that address will get filled with file contents which we can access through pBuffer.
       
        //Now pBuffer holds the data from the file.. We do whatever we want with it such as printing it.
        std::cout<<  pBuffer  <<std::endl;
        //Lets save it to a string.
        std::string DataHolder(pBuffer, FileSize);
        //Now we have to CLEAN UP our pointers by using Delete.
       
        delete[] pBuffer;    //Now pBuffer Pointers to nothing. We deleted the memory buffer than it pointed to!
    }


    Next is pointers to classes/objects. Lets say we want to allocate an array of objects but we do not know the size before hand. Well we can only do that by creating a pointer to our class. The operator to note here is the --> operator. This operator is "Pointer by" operator.

    If we have a pointer to an object right and we want to access the data the our pointer points to, we use the pointed by operator:

    C++ Code:
    typedef union RGB
    {
        int Color;
        struct
        {
            unsigned char Blue, Green, Red, Alpha;
        } Inner;
    } PRGB;                //PRGB is an object (pointer in some cases).



    int main()
    {
        PRGB A = new RGB[10];        //this is the essentially same as RGB* A. Like I said before, it's a pointer.
        RGB B;        //This is just a normal class object. It is not a pointer.
       
        std::cout<< A[0]->Inner.Blue;        //We cannot do A[0].Inner.Blue because A is a pointer to an array of the RGB struct and we must go through A and get the data it points to.
        std::cout<< B.Blue;            //We can definitely do this. Blue is a member of object B.

    delete[] A;  //Pointers to dynamic memory must be cleaned! Thus the memory that is pointed to by A is deleted with this command.
        //See the difference? A Pointers to an RGB structure and inorder to get the value of Blue, we have to find out what A Points to. Inother words, B is "pointed to by" A.

        RGB* M = new RGB;    //Dynamic allocation of an object M. Note that M is just a pointer to an RGB struct. It is not a pointer to an array of RGB struct. Also note that I did not use PRGB M. This is because PRGB is a pointer to an Object of type RGB. RGB* M = new RGB declares that M is now a pointer to an object of type RGB. It does not make sense to do PRGB M = new RGB; Without the index operator []. M is a single object, A is an array of objects.
        cout<<M->Inner.Blue;  //Inner.Blue is pointed to by M. Thus -> Must be used to access them. We still have to go through M to get to Blue.
        delete M;                        //Delete dynamically allocated memory which is pointed to by M. Again note that we do not have [] because it is not an array.
    }


    Now lets do the simple operations on poitners shall we? Here's some compilable code. Lets analyze it.

    C++ Code:
    #include <iostream>

    using namespace std;

    int main()
    {
        int B[5] = {9, 6, 7, 4, 11};      //Declare B as an array of Integers;

        int *P = B;                       //P Points to the location of B[0]. Yes, that's correct. P Points to the address of the very first value of the array.

        cout<< P <<endl;                  //Will print some giberish hexedecimal stuff. This represents the address of B[0]. Like I said before.

        cout<< *P <<endl;                 //We derefence P. So this means *P is the same as B[0]. Thus *P = 9;

        cout<< ++*P <<endl;               //We incremeted the value of *P. Since *P = B[0] which has a value of 9. ++*P = 10;

        P++;                              //Make P Point to the next Location in our Array. AKA the address of B[1] in memory.

        cout<< *P <<endl;                 //*P is now equal to 6. Since cell B[1] has a value of 6.

        *P = 99;                          //Change the value of Cell #2 to 99.

        cout<< B[1];                      //This is cell #2. It has a value of 99 since we indirectly changed it.
    }


    For more on Pointers just reply here and I'll clear it up as much as possible or you can read my tutorial and some others:

    My Project Tutorial Website:
    http://j1662736.gblearn.com/comp1229...nt1/Cpp09.html

    Other useful websites:
    http://www.cplusplus.com/doc/tutorial/pointers/

    Just leave a reply here if u need clarification or more help. Do not worry if it looks scary or anything, it's not dangerous to play around and test pointers. If it's hard at first, it's expected as it was also hard for me to grasp until about 3 days later. For my friends it took them a week or more since they didn't want to ask for help.

    Its always better to ask for help so don't be afraid to ask if you have more questions.
    Last edited by Brandon; 06-26-2012 at 04:57 AM.
    I am Ggzz..
    Hackintosher

  3. #3
    Join Date
    Dec 2011
    Location
    -bash
    Posts
    515
    Mentioned
    0 Post(s)
    Quoted
    27 Post(s)

    Default

    So helpful Brandon! I thank you for that

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •