All about Pointers

Manish Goyal

Manish Goyal

@manish-r2Hoep Oct 27, 2024
Let us discuss everything about pointers, starting from basic definition to each and every error that generally occurs while doing programming in c++ through this thread


I am sure it will help a lot of students

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • Manish Goyal

    Manish Goyal

    @manish-r2Hoep Jan 16, 2011

    No reply so far

    come on guys ,didn't you find any problem while working with pointers?If yes, then share it
  • sachin bankar

    sachin bankar

    @sachin-bankar-tI6gke Jan 20, 2011

    Pointer is a variable which holds address of another variable
  • Ankita Katdare

    Ankita Katdare

    @abrakadabra Jan 20, 2011

    Thank you Goyal for starting this thread.
    Everyone learning C or C++ faces problems with pointers at the beginner level.

    Could someone start with explaining the basics of pointers and their various forms?
  • Deepika Bansal

    Deepika Bansal

    @deepika-jf1ysv Jan 20, 2011

    Pointers have some relation with with 1D and 2D arrays. I'm quoting the example of a C++ program.
    void main()
    {
    int a[5];    //creating an integer array to store upto 5 integers
    cout<<a;   //output is the memory address of the element a[0] ie starting address of array
    
    //one way to access elements of array
    for(int i=0;i<5;i++)
      cout<<a[i];
    
    //another way using pointers
    for(int i=0;i<5;i++)
      cout<<*(a+i);   //*(a+i) is equivalent to a[i]
    }
    
    This was the case of static sized arrays ie size of the array is known at the compile time.
    eg:- consider the following code-->
    //this is okay
    const int size=5;   //creating a constant variable
    int a[size];
    
    //but this is wrong
    int size=5;
    int a[size];
    
    so to create dynamic arrays (eg when size has to be known from the user), we make use of pointers as-->
    int size;
    int *a;   //uninitialized pointer
    cout<<"Enter the size of the array: ";
    cin>>size;   //got the array size from the user
    a=new int[size];  //a can now hold upto 'size' number of variables
    
    //now the elements of 'a' can be accessed in any of the 2 ways discussed above.
    
    Also there is a difference between int a=new int[size]; and int a=new int(size);
    int a=new int[size]; will create an array 'a' of size/length='size'.
    but int a=new int(size); will create an int variable ie only 2 bytes will be allocated to 'a' whose value or memory content will be='size'.


    PS: It's been very long that I've revised my C++ concepts. If anyone finds any error or ambiguity, please do let me know.😀 Will try to post the maximum of my knowledge about pointers.😛