为什么即使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.