首页 > 解决方案 > 数组名作为指针

问题描述

我了解到数组的名称用作指针。
在 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;

}

标签: arrayspointerscharinteger

解决方案


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

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

2.上面的语句你正在做显式类型转换!您正在将 char 数组转换为 void 指针。而 WKT,char 的大小为 1。所以地址增加了 1。仅供参考,数组名称的表示法,例如's'等于&s [0]。(第一个索引的地址),它也等于数组名称的地址(&s)。

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

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

推荐阅读