为什么即使sizeof相同,指针也不能适合不同类型的变量? [英] Why can't pointer fit variable of different type, even though sizeof is same?

查看:100
本文介绍了为什么即使sizeof相同,指针也不能适合不同类型的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么任何指针的大小为4或8个字节,但不能容纳任何其他变量?尝试为双指针分配int指针值时出现错误.

Why the sizeof any pointer is 4 or 8 bytes, but it cannot fit any different variable? I get error while trying to assign a double pointer an int pointer value.

int          *int_ptr{nullptr};
float        *float_ptr{nullptr};
double       *double_ptr{nullptr};
long double  *long_double_ptr{nullptr};
string       *string_ptr{nullptr};
vector<int>   *vector_ptr{nullptr};

cout << "sizeof int pointer is " << sizeof int_ptr;    //8 or 4
cout << "sizeof float pointer is " << sizeof float_ptr;    //8 or 4
cout << "sizeof double pointer is " << sizeof double_ptr;    //8 or 4
cout << "sizeof double double pointer is " << sizeof long_double_ptr;    //8 or 4
cout << "sizeof string pointer is " << sizeof string_ptr;    //8 or 4
cout << "sizeof vector int pointer is " << sizeof vector_ptr;  //8 or 4

double double_num{1020.7};
double_ptr = &int_ptr;      //cannot convert ‘int**’ to ‘double*’ in assignment

推荐答案

C ++是一种静态类型的语言.该语言通过拒绝不相关类型之间的任意转换来增强类型安全性并保护您避免错误.类型的含义并不能仅通过大小来完全描述.

C++ is a statically typed language. The language enforces type safety and protects you from mistakes by rejecting arbitrary conversions between unrelated types. The meaning of a type is not wholly described by the size alone.

如果地址包含类型为int*的对象,则int**可以指向该对象.假定该地址包含一个int*类型的对象,它就不可能也包含一个double类型的对象,因此没有有意义的方法将这些指针之一转换为另一个指针.

If an address contains an object of type int*, then a int** can point to that object. Given that the address contains an object of type int*, it cannot possibly also contain an object of type double, so there is no meaningful way to convert one of those pointers to another.

这篇关于为什么即使sizeof相同,指针也不能适合不同类型的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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