为什么在C++中,arrayname[i]不等于*(arrayname+i)

Why arrayname [i] does not equal to *(arrayname + i) in this case in C++

本文关键字:不等于 arrayname+i C++ arrayname 为什么      更新时间:2023-10-16

对于以下代码,为什么在这种情况下arrayname[i]不等于*(arrayname+i),并且输出可能很奇怪:

#include <iostream>
using namespace std;
struct fish
{
    char kind[10] = "abcd";
    int weight;
    float length;
};
int main()
{
    int numoffish;
    cout << "How many fishes?n";
    cin >> numoffish;
    fish *pfish = new fish[numoffish];
    cout << pfish[0].kind << endl; //the output is "abcd"
    /*if the above code is changed to
    "cout << (*pfish.kind);"
     then compile error happens */
    /*and if the above code is changed to
    "cout << (*pfish->kind);"
    then the output is only an "a" instead of "abcd"*/
    delete [] pfish;
    return 0;
}

.运算符和->运算符的优先级高于一元*运算符。

在访问等成员之前,您必须添加括号以计算*

cout << ((*pfish).kind);

(*pfish).kind等于pfish[0].kind

*pfish.kind等于*(pfish.gind),并且pfish是指针类型,因此需要在其上使用运算符->,而不是运算符访问它的成员,所以你的编译器抱怨它。

另外,*pfish->kind是*(pfish->kind),pfish->kind是char[10]类型的"abcd",所以如果它是一个char,那么它等于pfish->kind[0],所以它只输出"a"。

C++运算符优先级:http://en.cppreference.com/w/cpp/language/operator_precedence