對於下面的代碼,爲什麼在這種情況下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不同 –