在字符指针数组的情况下,“数组名称"是什么意思?

编程入门 行业动态 更新时间:2024-10-20 16:33:56
本文介绍了在字符指针数组的情况下,“数组名称"是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在我的代码中:

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:

  • 为什么会有不同?
  • str 和 str[0] 都是字符指针,对吧?
  • Why is there a difference?
  • 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.

    更多推荐

    在字符指针数组的情况下,“数组名称"是什么意思?

    本文发布于:2023-07-28 02:36:18,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1226511.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:数组   指针   字符   情况下   名称

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!