对于下面的代码,为什么在这种情况下arrayname [i]不等于*(arrayname + i)很奇怪:为什么在这种情况下,在C++中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;
}
您的代码与您的问题不符。你正确地说'a [i]'和'*(a + i)'是一样的。你的代码包含'pfish [0]',根据该规则与'*(pfish + 0)'相同。到现在为止还挺好。但是你的代码示例包含'(* pfish.kind)',它与'*(pfish + 0)'完全不同。 –
@ M.M是的,我明白了,谢谢。我只是没有意识到(* pfish.kind)与(* pfish).kind不同 –