为什么在C++中,arrayname[i]不等于*(arrayname+i)
Why arrayname [i] does not equal to *(arrayname + i) in this case in 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;
}
.
运算符和->
运算符的优先级高于一元*
运算符。
在访问等成员之前,您必须添加括号以计算*
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
相关文章:
- 为什么 std::round(sin(pi/6)) 不等于 1?
- 你怎么编码,如果x不等于一个数字,程序就会退出
- u张量模型输出不等于预期输出
- 虽然不等于陈述和/或差异
- 这种关系不等于定义良好的表达式吗?
- OpenGL 版本不等于支持的着色器版本
- 两个 4 位位字段加起来不等于一个字节的大小 - 如何修复?
- 如果整数不等于 0,则将其减小为 1
- C 循环虽然不等于任何两个值
- vb.net单不等于c float
- 如何获取C编译器#Error如果大小(struct ..)不等于给定的数字
- C++ 而语句不等于检查
- 有没有办法检查int是否不等于数组中的所有值?(C )
- 整数数组中的元素数量不等于其大小
- 获取不等于特定值的向量的第一个N元素
- 使用 boost 解析符号链接时,结果不等于原始路径名
- 什么是有效的检查:等于或不等于
- 发送的字节不等于C 套接字PRG中的接收字节
- 奇怪的不等式 - WC_BUTTONW不等于 L "Button" ?
- 为什么在C++中,arrayname[i]不等于*(arrayname+i)