gpt4 book ai didi

c++ - 为什么数组名 [i] 在这种情况下在 C++ 中不等于 *(arrayname + i)

转载 作者:太空宇宙 更新时间:2023-11-04 16:04:52 25 4
gpt4 key购买 nike

对于下面的代码,为什么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);

关于c++ - 为什么数组名 [i] 在这种情况下在 C++ 中不等于 *(arrayname + i),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37234262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com