Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

c++ - Why is the data type needed in pointer declarations?

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 memory accordingly.

But in the case of pointers, we know that their size is constant (eg. 2 bytes in "Turbo Compiler"), irrespective of the data type of the variable it is pointing to, because the pointer is storing a memory address as an unsigned integer.

My question is, if the pointers are always a constant size in bytes, then what is the need of mentioning the data type while declaring them? Is my understanding about pointers wrong?

question from:https://stackoverflow.com/questions/9802585/why-is-the-data-type-needed-in-pointer-declarations

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Data type is needed when dereferencing the pointer so it knows how much data it should read. For example dereferencing a char pointer should read the next byte from the adress it is pointing to while an int pointer should read 2 bytes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...