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

Categories

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 store the address of variables, and address occupies same amount of memory whatever may be the type. So, why do we need to declare its type?

See Question&Answers more detail:os

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

1 Answer

Type-safety. If you don't know what p is supposed to point to, then there'd be nothing to prevent category errors like

*p = "Nonsense";
int i = *p;

Static type checking is a very powerful tool for preventing all kinds of errors like that.

C and C++ also support pointer arithmetic, which only works if the size of the target type is known.

address occupies same amount of memory whatever my be the type

That's true for today's popular platforms. But there have been platforms for which that wasn't the case. For example, a pointer to a multi-byte word could be smaller than a pointer to a single byte, since it doesn't need to represent the byte's offset within the word.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...