为什么指针声明中需要数据类型? [英] Why is the data type needed in pointer declarations?

查看:157
本文介绍了为什么指针声明中需要数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,在C/C ++中,当声明一个变量时,我们需要声明其数据类型,这告诉编译器相应地在内存中保留字节数.

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.

但是对于指针,我们知道它们的大小是恒定的(例如,"Turbo Compiler"中为2个字节),而与它指向的变量的数据类型无关,因为指针将内存地址存储为无符号整数.

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?

推荐答案

在取消引用指针时需要使用数据类型,以便知道应该读取多少数据.例如,取消引用char指针应从其指向的地址中读取下一个字节,而int指针应读取2个字节.

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.

这篇关于为什么指针声明中需要数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆