Why is the data type needed in pointer declarations?

前端 未结 8 675
萌比男神i
萌比男神i 2020-12-04 22:07

As far as I know about data types in C/C++, while declaring a variable, we need to declare its data type, which tells the compiler to reserve the number of bytes in the memo

8条回答
  •  孤城傲影
    2020-12-04 22:26

    First of all the size and representation of the pointers themselves aren't always the same for different types. It's just something that happens on many implementations.

    Second, when using pointers you don't care about the size of the pointers themselves. You need the size of the pointed type.

    For example, try this:

    int var[5];
    char *c = (char *)var;
    int  *x = var;
    
    printf("%p\n%p\n", p + 1, x + 1);
    

    You'll see pointer arithmetic strongly depends on the size of the pointed type.

提交回复
热议问题