指针数组和大小混淆 [英] Pointer array and sizeof confusion

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

问题描述

为什么以下代码会输出 4

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

我有一个指针数组,但它应该有长度1,指针是一个指针。


解决方案

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



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



**指针是一个char。 sizeof(** pointer)将为1.请注意**指针是一个字符,因为它被定义为 char **



请注意, sizeof 是一个编译器运算符。它在编译时被渲染为常量。在运行时可以更改的任何内容(如新数组的大小)不能使用 sizeof 来确定。



注意2:如果你定义为:

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

现在指针之前,但现在你可以说:

  int arraySize = sizeof //数组的总空间大小
int arrayLen = sizeof(array)/ sizeof(array [0]); // number of element == 1这里。


Why does the following code output 4?

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

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

解决方案

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

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

**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.

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.

Note 2: If you had defined that as:

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

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.

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

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