問(wèn)題描述
我剛剛讀到我們需要在 C(或 C++)中聲明指針時(shí)給出指針的類型,即:
I just read that we need to give the type of pointers while declaring them in C (or C++) i.e.:
int *point ;
據(jù)我所知,指針存儲(chǔ)變量的地址,無(wú)論類型如何,地址都占用相同數(shù)量的內(nèi)存.那么,為什么我們需要聲明它的類型?
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?
推薦答案
類型安全.如果你不知道 p
應(yīng)該指向什么,那么就沒(méi)有什么可以防止像
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;
靜態(tài)類型檢查是防止此類錯(cuò)誤的非常強(qiáng)大的工具.
Static type checking is a very powerful tool for preventing all kinds of errors like that.
C 和 C++ 還支持指針運(yùn)算,它僅在目標(biāo)類型的大小已知時(shí)才有效.
C and C++ also support pointer arithmetic, which only works if the size of the target type is known.
地址占用相同數(shù)量的內(nèi)存,無(wú)論我是什么類型
address occupies same amount of memory whatever my be the type
對(duì)于當(dāng)今流行的平臺(tái)來(lái)說(shuō)確實(shí)如此.但有些平臺(tái)并非如此.例如,指向多字節(jié)字的指針可能比指向單字節(jié)的指針小,因?yàn)樗恍枰硎咀衷谧謨?nèi)的偏移量.
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.
這篇關(guān)于聲明類型的指針?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!