Declaring type of pointers?

前端 未结 10 2088
花落未央
花落未央 2020-12-01 05:20

I just read that we need to give the type of pointers while declaring them in C (or C++) i.e.:

int *point ;

As far as I know, pointers sto

10条回答
  •  误落风尘
    2020-12-01 06:01

    The type of pointer comes to play while dereferencing and pointer arithmetic. For example

    int x=10;     //Lets suppose the address of x=100
    int *ptr=&x;   //ptr has value 100
    printf("The value of x is %d", *ptr);
    ptr++;  // ptr has value 104(if int is 4bytes)
    

    In the above example the pointer type is int so the compiler will start looking for the values stored in the next 4 bytes(if int is 4bytes) starting from memory address 100. So the type of pointer tell the compilers that how many bytes its should look for while dereferencing. If the pointer type was not there how would the compiler would have known that how many bytes to look while dereferencing. And when we did ptr++ the type of pointer tells by how much the ptr should be incremented. Here ptr is incremented by 4.

    char c='a';   //Lets suppose the address of c = 200
    char* ptr=&c;   //ptr has value 200
    ptr++;   //ptr has value 201(char assumed to be 1 byte) 
    

    The pointer type tells that ptr is incremented by 1 byte.

提交回复
热议问题