T. Yu
T. Yu

Reputation: 53

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

For the following code, why arrayname [i] does not equal to *(arrayname + i) in this case and the output can be strange:

#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;
}

Upvotes: 0

Views: 67

Answers (2)

Xdminsy
Xdminsy

Reputation: 83

(*pfish).kind is equal to pfish[0].kind

*pfish.kind is equal to *(pfish.kind), and pfish is of pointer type, so you need to use operator -> on it rather than the operator . to access it's member, and so your compiler complained about it.

Also *pfish->kind is *(pfish->kind), pfish->kind is "abcd" of type char[10], so dereferencnig it is a char, it is equal to pfish->kind[0], so it only outputed 'a'.

C++ operator precedence: http://en.cppreference.com/w/cpp/language/operator_precedence

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

The . operator and -> operator have higher precedence than unary * operator.

You have to add parentheses to have * calculated before accessing members like

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

Upvotes: 4

Related Questions