Why is the data type needed in pointer declarations?

前端 未结 8 659
萌比男神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:36

    The problem is not about pointer size but pointer dereferencing. (wether in C or C++)

    Say you have:

    int* someint;
    float* somefloat;
    

    *someint references a memory size of sizeof(int), whereas *somefloat references a memory size of sizeof(float) which are different.

    0 讨论(0)
  • 2020-12-04 22:51

    What size a pointer needs depends on the system you are using. On a x86_64 system the pointer size might by 64 bit.

    The reason why you need the data type for pointers is because the compiler has to know what the size of the memory cell is, among others, the pointer is pointing to. Also type safety cannot be ensured w/o the type. Also, you would have to typecast every pointer when accessing structures from the pointer.

    You also could use a void pointer and do everything by hand. But why should you want that?

    0 讨论(0)
提交回复
热议问题