在字符指针数组的情况下,“数组名称"是什么意思? [英] What does the 'array name' mean in case of array of char pointers?

查看:25
本文介绍了在字符指针数组的情况下,“数组名称"是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中:

 char *str[] = {"forgs", "do", "not", "die"};
 printf("%d %d", sizeof(str), sizeof(str[0]));  

我得到的输出为 12 2,所以我的怀疑是:

I'm getting the output as 12 2, so my doubts are:

  1. 为什么会有不同?
  2. strstr[0] 都是字符指针,对吧?
  1. Why is there a difference?
  2. Both str and str[0] are char pointers, right?

推荐答案

在大多数情况下,数组名会衰减到它的第一个元素的地址的值,并且 type 与指向元素类型的指针相同.因此,您会期望一个裸 str 的值等于 &str[0],并且类型指针指向 char 的指针.

In most cases, an array name will decay to the value of the address of its first element, and with type being the same as a pointer to the element type. So, you would expect a bare str to have the value equal to &str[0] with type pointer to pointer to char.

然而,sizeof 并非如此.在这种情况下,数组名称保持其 sizeof 的类型,这将是指向 char 的 4 个指针的数组.

However, this is not the case for sizeof. In this case, the array name maintains its type for sizeof, which would be array of 4 pointer to char.

sizeof 的返回类型是 size_t.如果你有C99编译器,你可以在格式字符串中使用%zu打印sizeof返回的值.

The return type of sizeof is a size_t. If you have a C99 compiler, you can use %zu in the format string to print the value returned by sizeof.

这篇关于在字符指针数组的情况下,“数组名称"是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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