指针数组和sizeof混淆

2023-02-23C/C++开发问题
4

本文介绍了指针数组和sizeof混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

为什么下面的代码输出4?

Why does the following code output 4?

char** pointer = new char*[1];
std::cout << sizeof(pointer) << "
";

我有一个指针数组,但它的长度应该是 1,不是吗?

I have an array of pointers, but it should have length 1, shouldn't it?

推荐答案

pointer 是一个指针.它是指针的大小,在您的系统上为 4 个字节.

pointer is a pointer. It is the size of a pointer, which is 4 bytes on your system.

*pointer 也是一个指针.sizeof(*pointer) 也将是 4.

*pointer is also a pointer. sizeof(*pointer) will also be 4.

**pointer 是一个字符.sizeof(**pointer) 将是 1.注意 **pointer 是一个字符,因为它被定义为 char**.new`ed 数组的大小永远不会进入这个.

**pointer is a char. sizeof(**pointer) will be 1. Note that **pointer is a char because it is defined as char**. The size of the array new`ed nevers enters into this.

注意 sizeof 是一个编译器操作符.它在编译时呈现为常量.任何可以在运行时更改的内容(例如新数组的大小)都无法使用 sizeof 来确定.

Note that sizeof is a compiler operator. It is rendered to a constant at compile time. Anything that could be changed at runtime (like the size of a new'ed array) cannnot be determined using sizeof.

注 2:如果您已将其定义为:

Note 2: If you had defined that as:

char* array[1];
char** pointer = array;

现在 pointer 的值与以前基本相同,但现在您可以说:

Now pointer has essencially the same value as before, but now you can say:

 int  arraySize = sizeof(array); // size of total space of array 
 int  arrayLen = sizeof(array)/sizeof(array[0]); // number of element == 1 here.

这篇关于指针数组和sizeof混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6