【问题标题】:Name of array as pointer数组名作为指针
【发布时间】:2020-02-15 02:34:51
【问题描述】:

我了解到数组的名称用作指针。
在 C++ 中,当我创建整数类型数组名 'a' 时,cout a 会打印出数组的地址。
但是当我创建 char 类型数组名 's' 时,cout s 会打印出数组的内容而不是地址。
我想知道为什么会这样。

#include <iostream>

using namespace std;

int main()
{
    // a string is a sequence of characters.
    char s[4] = "abc"; // why not giving 3 as the size of the array?

    // what if you want to print the address?
    cout << '\n';
    cout << (void*) s << "\n"; // Treat 's' as a void* variable.
    cout<<(void*)&s<<endl;
    cout << (void*)&s[0] << "\n"; // This also works.
    cout << (void*)&s[1] << "\n";
    cout<endl;


    cout << s << "\n"; // Treat 's' as a void* variable.
    cout<<&s<<endl;
    cout << &s[0] << "\n"; // This also works.
    cout << &s[1] << "\n";

    return 0;

}

【问题讨论】:

  • 我认为cout 使用了一个模板函数,它以不同的方式处理char 数组。
  • 关于“为什么不给 3 作为数组的大小”的问题 - 这是因为以空字符结尾的字符串 "abc" 的长度为 4 个字符(预处理器隐含地添加了一个空字符)。
  • 顺便说一下,对于静态声明的数组x(即,其大小指定为常数),x&amp;x 的值在技术上是相同的(相同的内存地址)。

标签: arrays pointers char integer


【解决方案1】:

1. 字符串常量总是以 null('\0') 值结尾。 如果你不想要这个 Null 值,你可以像下面这样赋值

char s1[3] = {'a','b','c'};

2.Above 声明您正在执行显式类型转换! 您正在将 char 数组转换为 void 指针。 而WKT,char的大小为1。所以地址增加了 成为一个。仅供参考,数组名称的符号(例如's')等于 &s[0].(第一个索引的地址),它也等于地址 数组名 (&s)..

[s == &s == &s[0]]

  1. 而且我们知道,void 指针可以保存任何类型的地址,并且可以类型转换为任何类型。但是在将字符转换为 void 指针时,我们只看到地址转换。因为 &s 和 s 只保存第一个字符的地址。此外,cout 无法识别该值是字符值。

【讨论】:

    猜你喜欢
    • 2011-05-10
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    • 2010-12-15
    • 2011-05-24
    相关资源
    最近更新 更多