【问题标题】:Why pointer is returning String and not the first char since pointer is storing address of first char only?为什么指针返回字符串而不是第一个字符,因为指针仅存储第一个字符的地址?
【发布时间】:2021-03-07 07:38:48
【问题描述】:

我是 C++ 新手。据我所知,上述情况names[0] 应该是'R' 的索引。 我想我错过了或缺乏知识。 请帮帮我。

#include<iostream>

using namespace std;

int main() {
    char *names[] = {
            "Rohan",
            "Sammy",
            "Samuel",
            "Henil"
    };

    // Expected R to be printed and not Rohan
    cout << *names << endl;
    return 0;
}    

输出:

Rohan

【问题讨论】:

  • names 是一个数组。所以,在*names names 已经衰减为一个指针。因此,它的类型为char**
  • 仅供参考,您的代码无法在 C++11 及更高版本中编译,因为您无法将字符串文字分配给非常量 char*。改用const char*const char* names[] = {"Rohan", ...};

标签: c++ c string pointers char


【解决方案1】:

你只需要放括号 *names[0]

[代码]:

#include<iostream>
#include<string>
using namespace std;
int main(){
    char* names[] = {
        "Rohan",
        "Sammy",
        "Samuel",
        "Henil"
    };
   
       
    //   Expected R to be printed and not Rohan
       cout<<*names[0]<<endl;
    return 0;
}

[结果]:

R

Live demo here!

【讨论】:

    【解决方案2】:

    据我所知,在上述情况下,names[0] 应该是 'R' 的索引

    names[0] 不是索引。它是一个指针。它指向字符串文字中的字符R

    当一个指针被插入到一个字符流中时,行为不是流式传输指向的对象。

    当您将指向 char 的指针插入到字符流中时,它被假定为指向以 null 结尾的字符串的指针,并且行为是流式传输整个字符串。你应该相应地调整你的期望。

    附:该程序自 C++11 以来格式错误,因为字符串文字不能隐式转换为 char*

    【讨论】:

      【解决方案3】:

      按名称引用数组将衰减指向指向数组第一个元素的指针。所以,names&amp;names[0] 相同,因此*namesnames[0] 相同,这是数组中的第一个char* 元素,而不是数组中第一个字符串的第一个char数组。

      【讨论】:

        猜你喜欢
        • 2021-06-28
        • 1970-01-01
        • 1970-01-01
        • 2020-07-27
        • 2017-07-19
        • 1970-01-01
        • 2012-03-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多