What exactly is the purpose of the (asterisk) in pointers?

前端 未结 4 1179
有刺的猬
有刺的猬 2020-12-09 14:00

I\'m new to programming and I\'m trying to wrap my head around the idea of \'pointers\'.


int main()
{
    int x = 5;
    int *pointerToInteger = &         


        
4条回答
  •  攒了一身酷
    2020-12-09 14:32

    yes the asterisk * have different meanings while declaring a pointer variable and while accessing data through pointer variable. for e.g

    int input = 7;
    int *i_ptr = &input;/*Here * indicates that i_ptr is a pointer variable 
                         Also address is assigned to i_ptr, not to *iptr*/ 
    cout<<*i_ptr;/* now this * is fetch the data from assigned address */
    cout<
    • for e.g if you declare like int *ptr = 7; its wrong(not an error) as pointers ptr expects valid address but you provided constant(7). upto declaration it's okay but when you go for dereferencing it like *ptr it gives problem because it doesn't know what is that data/value at 7 location. So Its always advisable to assign pointers variable with valid addresses. for e.g

      int input = 7; int *i_ptr = &input; cout<<*i_ptr;

    • for example char *ptr = "Hello"; => here * is just to inform the compiler that ptr is a pointer variable not normal one & Hello is a char array i.e valid address, so this syntax is okay. Now you can do

      if(*ptr == 'H') { /*....*/ } else { /*.... */ }

提交回复
热议问题